API Key Security Best Practices
API keys are the simplest form of API authentication and the most commonly mismanaged. They are easy to generate, easy to leak, and hard to revoke once exposed.
Never Hardcode API Keys
Keys in source code end up in version control, CI logs, container images, and client bundles.
// BAD
const API_KEY = "sk_live_abc123def456";
// GOOD
const API_KEY = process.env.PAYMENT_API_KEY;
Use environment variables, secrets managers, or vault services:
- AWS Secrets Manager: AWS — Secrets Manager
- GCP Secret Manager: GCP — Secret Manager
- Azure Key Vault: Azure — Key Vault
- HashiCorp Vault: Vault — Documentation
Never Expose Keys in Client-Side Code
Any key in a browser bundle, mobile app binary, or NEXT_PUBLIC_ environment variable is public. Treat it as such.
If you need to call an external API from the browser, proxy through your own backend:
// app/api/weather/route.ts — proxy with server-side key
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const city = searchParams.get("city");
const res = await fetch(
`https://api.weather.com/v1/current?city=${encodeURIComponent(city ?? "")}`,
{
headers: { Authorization: `Bearer ${process.env.WEATHER_API_KEY}` },
}
);
return new Response(await res.text(), {
headers: { "Content-Type": "application/json" },
});
}
Scope Keys to Minimum Permissions
Most API providers let you restrict what a key can do. Always scope keys down:
- Read-only vs read-write: if you only need to read data, create a read-only key.
- IP restrictions: restrict to your server IPs if the provider supports it.
- Resource restrictions: limit to specific buckets, projects, or APIs.
AWS example: use IAM policies to restrict what an access key can do:
Reference: AWS — IAM Best Practices
Google Cloud example: restrict API keys by service and IP:
Reference: GCP — Restricting API Keys
Rotate Keys Regularly
Rotation limits the window of exposure if a key is leaked:
- Generate a new key.
- Deploy the new key to all services.
- Verify everything works.
- Revoke the old key.
Automate this process. AWS Secrets Manager supports automatic rotation:
Reference: AWS — Rotate Secrets
Detect Leaked Keys
- GitHub Secret Scanning: automatically detects keys pushed to repositories: GitHub — Secret Scanning
- GitGuardian: scans for secrets in commits.
- truffleHog: open-source tool to scan git history for high-entropy strings.
Set up alerts so leaked keys are revoked within minutes, not days.
Prefix Keys for Identification
Use prefixes to identify key type and environment. This makes leaked keys easier to trace:
pk_live_... — public, production
sk_live_... — secret, production
pk_test_... — public, test
sk_test_... — secret, test
Stripe uses this pattern: Stripe — API Keys
Rate Limit and Monitor Usage
- Apply rate limits per key (not just per IP).
- Log all API key usage with timestamps and source IPs.
- Alert on unusual patterns: spikes in usage, requests from new IPs, requests to unusual endpoints.
- Implement usage quotas to prevent abuse.
Use Short-Lived Tokens Where Possible
If the API supports it, prefer short-lived tokens (OAuth, STS) over static API keys:
- AWS: use STS temporary credentials instead of long-lived access keys: AWS — STS
- GCP: use service account impersonation with short-lived tokens: GCP — Short-lived Credentials
Checklist
- No keys in source code or version control
- No keys in client-side code or
NEXT_PUBLIC_variables - Keys scoped to minimum permissions
- IP restrictions applied where supported
- Rotation schedule in place (90 days or less)
- Secret scanning enabled on repositories
- Rate limiting applied per key
- Usage logging and alerting configured
- Short-lived tokens used where available
Related Guides
Content is AI-assisted and reviewed by our team, but issues may be missed and best practices evolve rapidly, send corrections to [email protected]. Always consult official documentation and validate key implementation decisions before making design or security choices.
