flutter - Hiding Google API keys
Security problem
I often use the Google Sheets API because running a DB feels heavy for personal projects.
But in web publishing, the API key is exposed in dev tools.
I was glad I noticed it? but honestly, it just feels annoying.
.env
It’s not critical data, but if you know, you should handle it.
The simplest method I picked:
create a .env file and load it with Flutter’s dot_env package.
It works, but security is never perfect.
.env file structure
The tricky part is that API keys often contain \n.
It’s safer to ask ChatGPT for a template for both JSON and .env.
.dart file
var cremap = {
"type": dotenv.get("type"),
"project_id": dotenv.get("project_id"),
"private_key_id": dotenv.get("private_key_id"),
"private_key": dotenv.get("private_key"),
"client_email": dotenv.get("client_email"),
"client_id": dotenv.get("client_id"),
"auth_uri": dotenv.get("auth_uri"),
"token_uri": dotenv.get("token_uri"),
"auth_provider_x509_cert_url": dotenv.get("auth_provider_x509_cert_url"),
"client_x509_cert_url": dotenv.get("client_x509_cert_url"),
"universe_domain": dotenv.get("universe_domain")
};
var cremapJson = jsonEncode(cremap);
final gsheets = GSheets(cremapJson);
.env file
type = service_account
private_key = "-----BEGIN PRIVATE KEY-----\nMI
That’s it.
end.