Skip to main content

Command Palette

Search for a command to run...

API keys best practices notes

Published
2 min read
API keys best practices notes
T

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:

  1. Generate new key

  2. Update system to use new key

  3. Wait for old requests to finish

  4. 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.