Blog › Developer Security

API Key Security Best Practices for Developers

By Marcus Webb, Security AnalystJuly 9, 202610 min read

Leaked API keys are behind thousands of security incidents every year. GitHub's secret scanning has found millions of exposed credentials in public repositories. AWS keys left in code cost companies tens of thousands of dollars in unauthorized compute charges within hours of exposure. This guide covers everything you need to know to handle API keys safely.

New to API keys? Read API Keys Explained: What They Are & How They Work first — this guide assumes you already know what an API key is and focuses entirely on keeping them secure.

The most common mistake: committing keys to source code

Every week, developers accidentally commit API keys, database credentials, and secrets to public GitHub repositories. Automated bots scan every public commit in real time — your key can be stolen within seconds of being pushed.

Never do this:

// ❌ WRONG — never hardcode credentials
const stripe = new Stripe("sk_live_4eC39HqLyjWDarjtT1zdp7dc");
const openai = new OpenAI({ apiKey: "sk-proj-AbCdEfGhIjKlMnOp..." });

Always do this:

// ✅ CORRECT — load from environment variables
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

How to generate secure API keys

A secure API key must be:

  • Cryptographically random — generated by a CSPRNG (cryptographically secure pseudorandom number generator), not Math.random().
  • Long enough — at least 128 bits (16 bytes) of entropy. 256-bit (32-byte) keys are standard.
  • Unique — every key should be different and never reused.

Our API Key Generator creates cryptographically secure keys using crypto.getRandomValues() in hex, Base64, Base64URL, or alphanumeric formats.

Best practices for storing API keys

Environment variables

The standard approach for server-side code. Store secrets in a .env file locally, add .env to .gitignore, and use your hosting platform's secret management for production (Replit Secrets, Heroku Config Vars, AWS Secrets Manager, etc.).

Secret management services

For production systems, dedicated secret managers provide rotation, audit logs, and fine-grained access control: AWS Secrets Manager, HashiCorp Vault, Google Cloud Secret Manager, Azure Key Vault.

Never in client-side code

Any API key embedded in JavaScript that runs in a browser is publicly visible — users can view source, inspect network requests, or open DevTools to find it. Secret API keys must only live on your server.

If you need to call a third-party API from a browser app, proxy the request through your own backend server which holds the key.

Principle of least privilege

When creating API keys, grant the minimum permissions needed. Most APIs let you scope keys by capability:

  • A key for reading data shouldn't have write permissions
  • A key for one service shouldn't have access to another
  • Production keys shouldn't be used in development

This limits the blast radius of a leaked key — an attacker who gets a read-only analytics key can't delete your data or make purchases.

Key rotation

API keys should be rotated (replaced with a new key) periodically and immediately if:

  • You suspect the key may have been exposed
  • A team member who had access to the key leaves your organization
  • You find the key in a log file, error message, or version control
  • Your security policy requires periodic rotation

Detecting and responding to leaked keys

If you suspect a key has been leaked:

  1. Revoke the key immediately — don't wait to investigate first.
  2. Generate a new key and update your configuration.
  3. Review API usage logs for unauthorized activity during the exposure window.
  4. If financial damage occurred, contact the service provider immediately.
  5. If the key was committed to a public repository, contact GitHub support — even after you delete the commit, it may be cached.

Useful tools for detecting exposed secrets

  • • git-secrets — prevents committing AWS credentials and other patterns
  • • detect-secrets — scans your repo for potential secrets before you commit
  • • GitHub Secret Scanning — automatically notifies you if a key is pushed to a public repo
  • • truffleHog — searches git history for high-entropy strings that may be secrets

Frequently asked questions

What format should API keys be in — hex, Base64, or alphanumeric?

It depends on the context. Hex (0-9, a-f) is URL-safe and common. Base64URL (no padding) is compact and used in JWTs and OAuth. Alphanumeric (A-Z, a-z, 0-9) works in any context. All three are equally secure for the same number of bytes.

How long should an API key be?

A minimum of 128 bits of entropy (16 bytes, 32 hex chars). Most services use 256-bit keys (32 bytes, 64 hex chars). Longer keys don't hurt but rarely add practical security beyond 256 bits.

Should I hash API keys before storing them in my database?

Yes — this is best practice. Store only the hash (SHA-256 is sufficient here, since API keys are long random strings, not user passwords). This way, even if your database is breached, the attacker only gets useless hashes.

Can I use the same API key for development and production?

No. Use separate keys with separate permission scopes. If a development key is exposed (e.g., shared in a Slack message or committed to a dev branch), it won't affect your production environment.