API keys best practices notes

Just a guy who loves to write code and watch anime.
Always put API keys in request headers
Always put API keys in request headers. Then they're not visible in browser history, logs, etc:
fetch("https://api.carta.com/data", {
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
});
Never put them in URLs:
// Bad: Keys visible in logs and browser history
fetch("https://api.carta.com/data?api_key=123");
Eh, not frontend
For frontend code, don’t put sensitive keys in either request headers or the URL.
If you’re building something production ready where frontend needs to communicate with an external API, build a proxy backend yourself to handle the request to that external API.
I’m not encouraging it, but I’m also not gonna lie to you. For smaller side projects, I just put it in the request headers, even if it’s frontend code. Again, I’m not encouraging it, but for pet projects, I don’t mind it. It’s not like real users are using it.
Keep different keys for different environments
const config = {
development: {
apiKey: "dev_key_123", // Testing environment
rateLimit: 100,
},
production: {
apiKey: "prod_key_456", // Real data, real users
rateLimit: 10000,
},
};
Store keys securely
Store keys securely:
Use environment variables
Never commit to git
Never expose in frontend code
// Good: Load from environment
const apiKey = process.env.CARTA_API_KEY;
// Bad: Hardcoded in code
const apiKey = "abc123";
Rotate keys periodically
Rotate keys periodically:
Generate new key
Update system to use new key
Wait for old requests to finish
Delete old key
If keys are compromised, rotate them ASAP. They should expire, have a TTL/expiresAt. What's even better is to created short-lived keys on the fly. This is kind of what you do with access/refresh tokens. You use refresh tokens to get new access tokens. But access tokens are the ones you use for API requests.






