Stop Hardcoding API Keys Right Now
Cover photo by FlyD on Unsplash
Your source code is not a secure vault. If you check your API keys or database credentials into Git, you’ve already lost the battle. It’s a simple fact that is ignored far too often. Even a private repository is one accidental public push away from a disaster.
Why local files arent enough
I see developers rely on .env files for everything. These are great for local development, but they don’t solve the problem of distribution or rotation. If your code runs in a cloud environment, you shouldn’t be shipping secrets as flat files. You need a centralized way to inject these at runtime.
// Do not do thisconst apiKey = "sk_live_51M0x...";
// Do this insteadconst apiKey = process.env.STRIPE_SECRET_KEY;Keep secrets out of your build
“But I only have a small hobby project, so why do I need a key management service?” This is a valid objection. If you’re building a tiny personal site, a simple environment variable on your hosting provider is probably fine. You don’t need to overengineer this by spinning up a dedicated HashiCorp Vault instance. However, as soon as you have more than one person touching the codebase, the risk of credential leakage skyrockets.
I admit that setting up a proper key manager adds friction. It’s annoying to write scripts just to fetch your database password before the app boots up (or to configure your local CLI). Still, the cost of a leaked production key is orders of magnitude higher than the time you spend configuring these tools.
Use managed secrets
If you’re using AWS, look at Secrets Manager. For Azure, there is Key Vault. These services let you rotate keys without redeploying your entire application. They handle the audit logs too, so you know exactly which process touched your credentials and when.
# Example of fetching a secret with AWS CLIaws secretsmanager get-secret-value --secret-id prod/db-passwordDoes your architecture support rotation?
If your application requires a restart to pick up new keys, you aren’t really ready for dynamic rotation. That’s a structural limitation you should address eventually. Moving secrets out of the application code and into an external service forces you to build more resilient systems.
What happens when your provider’s API goes down and your app can’t fetch its keys? I’ve been there, and it’s a rough day at the office. You need to consider caching your secrets locally for a short duration while ensuring the application can gracefully retry requests. Are you testing your infrastructure for these kinds of intermittent failures?