PayAPIKey
Back to guides
Security9 min read

API Key Security Best Practices

Best practices for API key generation, storage, rotation, scopes, rate limits, logs, and leak response.

Treat API keys like production credentials

API keys are bearer credentials. Anyone who has the key can often use the API until the key is revoked, expired, or restricted. That makes API key security a product requirement, not just a documentation footnote.

A secure API key system combines prevention, detection, and recovery. Prevention reduces the chance of leaks. Detection helps find unusual usage quickly. Recovery gives users a clean way to rotate keys and limit damage.

Generate keys with enough entropy

Keys should be long, random, and generated with a cryptographically secure random source. Include a short prefix that identifies the environment or product, but do not make the secret portion predictable. Prefixes are useful because users can recognize a key without exposing the full secret.

  • Use separate live and test key prefixes.
  • Show the full secret only once at creation.
  • Store only a hash of the secret portion.

Limit what each key can do

Scopes and restrictions reduce blast radius. A reporting key should not be able to mutate data. A browser-exposed key should be domain-restricted and low privilege. A server key can have broader access, but it should still have limits and rotation rules.

ControlWhy it mattersExample
ScopesLimits actionsread:usage, write:messages
QuotasControls cost50k requests per month
IP allowlistLimits originOnly backend IPs
Domain restrictionReduces browser abuseOnly app.example.com
ExpirationForces rotation90-day temporary key

Log carefully

Logs are essential for billing and abuse detection, but they should not store full API keys. Store the key ID, prefix, workspace, route, usage units, response status, and timing. Redact secrets from request bodies, headers, traces, and customer support exports.

Have a leak response plan

When a key leaks, users need a fast path to revoke it and create a replacement. The product should show recent usage, affected scopes, and whether suspicious traffic occurred. Automated leak detection can watch public code hosts, logs, and sudden usage spikes, but manual rotation must still be simple.

  • Let users create overlapping keys before revoking the old one.
  • Notify workspace owners when a high-risk key changes.
  • Document how billing disputes are handled after a confirmed leak.