Skip to content

General

API Key Management: Best Practices to Store, Scope and Rotate Keys

How to generate, store, scope, rotate, monitor and revoke API keys, with checklists for secrets managers, environments, leaks and AI agent keys.

An API key is a long random string that tells an API which application is calling. It is simple to create and simple to use, and that is exactly the problem: anyone who holds the string can use it. Unlike a password typed by a person, a key is copied into config files, CI variables, chat messages and laptops, and it often lives for years.

API key management is everything you do around that string: how you generate it, where you store it, what it is allowed to do, how it travels over the network, how often it changes, who watches its usage and how you kill it when something goes wrong. This guide covers each of those steps in order, with the trade-offs, the tools that help and a checklist you can apply to your own keys today.

It is written for two kinds of readers: developers who consume keys from providers such as Stripe, OpenAI or a cloud platform, and teams that issue keys for their own API. Most practices apply to both; where they differ, the section says so.

Why API key management matters

A key is a bearer credential. Whoever presents it gets the access attached to it, with no second check that the caller is who they claim to be. That has a few consequences worth keeping in mind for everything that follows.

  • Copies are invisible. If a key is pasted into a public repository, a screenshot or a support ticket, nothing on the key itself tells you it has been copied.
  • Damage scales with scope. A read-only key for one resource leaks a little. An admin key for a payment account can cost real money within minutes.
  • Lifetime multiplies risk. A key that never expires stays useful to an attacker for as long as nobody notices it leaked.
  • Keys spread. One key used by five services, three developers and a CI pipeline has nine places it can leak from, and rotating it means touching all nine.

Good management does not try to make a leak impossible. It makes leaks less likely, keeps the damage of each leak small, shortens the time a leaked key is useful and makes it cheap to replace any key at any moment. If you want the wider picture beyond keys (authentication schemes, input validation, gateways), see the API security best practices guide and the overview of API authentication methods.

Common API key vulnerabilities

Most incidents involving keys come from a short list of mistakes. Knowing them up front tells you where to spend effort first.

Vulnerability Risk What happens Mitigation
Hardcoded keys in source High Anyone with repository access, or the whole internet for a public repo, gets the key Load keys from environment variables or a secrets manager
Keys in URLs High Keys land in server logs, proxy logs, browser history and analytics Send keys in a request header
Keys in client-side code High Anyone can read a key shipped in a web or mobile bundle Keep secret keys on the server, use a backend proxy
Weak or predictable keys Medium Keys can be guessed or brute forced Generate keys from a cryptographically secure random source
Excessive permissions Medium A leaked key can do far more than its job requires Scope each key to the least privilege
Shared keys across environments Medium A leaked development key opens production One key per environment and per service
No rotation or expiry Medium A leaked key stays useful indefinitely Expiry dates and automated rotation
No monitoring Medium Abuse goes unnoticed until the bill or the breach arrives Usage baselines, alerts and audit logs

These weaknesses compound. A hardcoded key with admin scope that never expires and that nobody monitors is far worse than any single item on the list. The rest of this guide works through them one by one.

Generate strong, identifiable keys

If you consume keys from a provider, generation is their job. If you issue keys for your own API, it is yours, and a few decisions here make every later step easier.

Use a secure random source

Keys must come from a cryptographically secure random number generator, never from timestamps, user IDs, hashes of predictable values or general purpose random functions. 32 bytes of randomness (256 bits) encoded as base64url or hex is a comfortable size.

JavaScript
import { randomBytes, createHash } from "node:crypto"

const secret = randomBytes(32).toString("base64url")
const key = `sk_live_${secret}`
const hash = createHash("sha256").update(key).digest("hex")

Add a recognizable prefix

A prefix such as sk_live_ or sk_test_ tells humans and tools what a key is and which environment it belongs to. Stripe and GitHub both use prefixes, and secret scanners rely on them to recognize leaked keys with few false positives. A prefix that encodes the environment also stops a test key from being mistaken for a live one.

Store a hash, show the key once

Treat issued keys like passwords. Store only a hash of the key (a fast hash such as SHA-256 is fine because the key is already high entropy), plus a short visible prefix so users can tell their keys apart in a dashboard. Show the full key exactly once, at creation, and never again. If your database leaks, the attacker gets hashes, not working keys.

Attach metadata from day one

Every key should carry an owner, a purpose, an environment, its scopes, a creation date and an expiry date. This costs nothing at creation and is the foundation for audits, rotation and incident response later.

Store keys in a secrets manager, never in code

The single most common way keys leak is by being committed to source control. Once a key is in a repository's history, deleting the line does not remove it; the key has to be rotated.

The minimum: environment variables

At the very least, load keys from the environment and keep local .env files out of git.

Shell
echo ".env" >> .gitignore
JavaScript
const apiKey = process.env.PAYMENTS_API_KEY
if (!apiKey) throw new Error("PAYMENTS_API_KEY is not set")

Environment variables keep keys out of the code, but they have limits: they are easy to print by accident in logs and crash reports, they are visible to every process in the same environment, and they give you no audit trail of who read them.

The standard: a dedicated secrets manager

A secrets manager is a service built to hold credentials. Common choices include HashiCorp Vault, AWS Secrets Manager, Azure Key Vault and Google Cloud Secret Manager. They share a common set of features:

  • Encrypted storage at rest, so the stored values are unreadable without the service's own keys.
  • Access control tied to identities, so a given service can read only the secrets it needs.
  • Audit logs of who read or changed each secret and when.
  • Versioning, so you can see past values and roll back.
  • Rotation support, either built in or through hooks.
  • Dynamic secrets in some tools: credentials generated on demand with a short lease that expire on their own.
Pros Cons
Removes secrets from repositories and config files Adds a service your applications depend on
One source of truth for every credential Can add latency when secrets are fetched
Makes rotation and revocation much easier Needs high availability planning to avoid a single point of failure
Detailed audit trails for compliance Requires setup effort and team buy-in

Tips for running a secrets manager well

  • Inject at deploy time. Let your CI/CD pipeline or orchestrator pull secrets and inject them into the runtime, so no human copies keys by hand.
  • Cache with a short TTL. Client-side caching keeps latency down without holding stale values for long.
  • Separate human and machine access. People and services should have different policies, and production secrets should be readable by production services only.
  • Plan for outages. Run the service with redundancy and document a break-glass procedure for emergency access.
  • Define it as code. Manage policies and secret paths with infrastructure as code so every environment is configured the same way.

Never ship secret keys to the client

Anything in a browser bundle or mobile app can be extracted. If a frontend needs to call an API that requires a secret key, route the call through your own backend, which holds the key and enforces its own checks. Some providers issue publishable keys designed for client use (Stripe's publishable keys are an example); those are the only keys that belong in client code.

Encrypt keys at rest and in transit

Encryption protects keys at the two moments they are most exposed: while stored and while moving between systems.

At rest

Secrets managers encrypt for you. If you must store keys or key material yourself, encrypt them with a strong algorithm such as AES-256 and keep the encryption key somewhere else. The usual pattern is envelope encryption: each secret is encrypted with a data key, and the data key is encrypted with a master key held in a key management service such as AWS KMS or Google Cloud KMS. The master key never leaves the KMS, so stealing the database alone is not enough.

Use separate encryption keys for development, staging and production, and review the setup periodically.

In transit

Every request that carries a key must use HTTPS with a modern TLS version. Reject plain HTTP outright on your API rather than redirecting, because by the time a redirect happens the key has already crossed the network in clear text. On your web properties, Strict-Transport-Security tells browsers to use HTTPS only.

Encryption also matters for compliance. Regulations such as GDPR and HIPAA require appropriate protection of sensitive data, and encrypting credentials is part of what auditors expect to see.

Send keys safely on every request

How a key is attached to a request decides where it can end up. The rules are short.

Use a header, never the URL

Http
GET /v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer sk_live_...

Query strings are recorded in web server logs, proxy logs, browser history, analytics tools and referrer headers. Headers are not logged by default. Send keys in Authorization or a dedicated header such as X-API-Key.

Redact keys in logs and errors

Configure your logging, tracing and error reporting to mask Authorization and any other header or field that can carry a credential. Check what your HTTP client prints in debug mode and what your framework includes in error pages, because those are common accidental leaks.

Stronger options for sensitive traffic

For high value or service-to-service traffic, a static key in a header may not be enough:

  • Request signing. Instead of sending the secret, the client signs each request with it (HMAC over the method, path, body and a timestamp). The secret never crosses the wire, and a captured request cannot be replayed later. AWS Signature Version 4 is a well known example.
  • Mutual TLS. Both client and server present certificates, so a stolen key is useless without the client's private key.
  • Token exchange. Use the long-lived key only to obtain a short-lived token (an OAuth 2.0 access token or a JWT with a short expiry) and use that token for the actual calls. A leaked token expires quickly.

These add complexity and may not work with older clients, so reserve them for the traffic that needs them.

Scope every key to the least privilege

The principle of least privilege says each key gets only the permissions its job requires. A key that only reads orders should not be able to issue refunds. If it leaks, the damage stays within that narrow scope.

What good scoping looks like

  • Resource level. Limit a key to specific resources: one repository, one bucket, one project.
  • Operation level. Separate read, write and delete. Many teams issue separate read and write keys.
  • Path level. Limit a key to certain endpoints, for example /v1/reports/*.
  • Time bound. Give keys an expiry, and grant elevated scopes only temporarily for a specific task.

Real providers support this. Stripe offers restricted keys limited to chosen resources with read or write access. GitHub's fine-grained personal access tokens can be limited to specific repositories and permissions and carry an expiry date. AWS IAM policies define exactly which services and actions a credential can use. Cloudflare API tokens are scoped to specific zones and permissions.

How to apply it in practice

  1. Start from zero. Create the key with no permissions and add only what fails without them.
  2. One key per consumer. Each service, integration or person gets its own key, so you can scope, monitor and revoke them independently.
  3. Use templates. Define standard permission sets for common jobs (reporting, billing sync, deployment) so nobody invents scopes ad hoc.
  4. Require a request for more. Expanding a key's scope should be a deliberate, recorded decision.
  5. Audit regularly. Permission creep is real: keys pick up extra scopes over time and rarely lose them. Review and trim on a schedule.
  6. Document the purpose. If nobody can say what a key is for, it is a candidate for revocation.

The trade-off is more keys and more administration. That cost is real but small compared to cleaning up after an admin key leaks.

Separate environments and restrict where keys work

One key per environment

Development, staging and production should never share keys. Each environment gets its own keys, ideally its own secret store, and permissions that match its risk. A developer may have broad access to development data and read-only access, or none, in production.

This limits the blast radius. A development key accidentally pushed to a public repository should open nothing that matters. Providers make this easy: Stripe separates test and live keys, and test keys cannot touch live payment data.

Practical habits help:

  • Use distinct names such as dev_api_key and prod_api_key, and prefixes inside the keys themselves.
  • Tag keys with environment metadata so they are easy to find and revoke.
  • Provision keys through your CI/CD pipeline and infrastructure as code, not by hand.
  • Use visual cues (colour, labels) in internal dashboards so nobody confuses production with staging.

Context-aware restrictions

Beyond scopes, you can limit where and when a key is accepted:

  • IP allowlists. Accept a key only from known addresses or CIDR ranges, such as your servers' egress IPs.
  • Private networking. Cloud features such as AWS PrivateLink, Azure Private Link and Google Cloud VPC Service Controls keep API traffic off the public internet entirely.
  • Referrer and app restrictions. For browser or mobile keys, some providers let you limit a key to specific domains or app identifiers.
  • Geography and time. Restrict sensitive operations to expected regions or business hours where that matches your usage.

These controls combine something you have (the key) with somewhere you are (an approved network). A stolen key used from an attacker's machine simply fails.

They have costs. Dynamic IPs, serverless platforms and remote teams make allowlists harder to maintain, and overly tight rules can lock out legitimate users. Use tiered restrictions based on sensitivity, manage ranges in CIDR notation, document the network dependencies and keep an emergency override for business continuity.

Rotate and expire keys on a schedule

Rotation means replacing a key with a new one and retiring the old one. Expiry means a key stops working on a set date whether or not anyone remembers it. Together they cap how long a leaked key stays useful, and they force regular review of who still needs access.

Pick a schedule by sensitivity

There is no single right interval. The schedule should reflect what the key protects, your regulatory requirements and how painful rotation is for your systems.

Key type Typical rotation
Production keys with access to sensitive data or money Every 30 to 90 days, or use short-lived credentials
Internal service keys with limited scope Every few months
Low risk, read-only keys Every 6 to 12 months
Any key after a suspected exposure Immediately

Many teams use 30 to 90 days for sensitive keys. If rotation is fully automated, shorter is better; if it is manual and painful, fix the automation first, because a schedule nobody follows protects nothing.

Rotate without downtime

The safe pattern uses an overlap period:

  1. Generate the new key and store it in the secrets manager.
  2. Deploy consumers so they use the new key. During this window both keys are valid.
  3. Watch usage of the old key until it drops to zero.
  4. Revoke the old key.

This requires that your API accept two active keys per consumer, and that clients read the key from configuration rather than from code. Send expiry warnings to key owners ahead of time, keep a version history of keys for troubleshooting, and tell external consumers before you rotate a key they hold.

Automate the lifecycle

Manual rotation is where human error creeps in: a forgotten service, a key pasted in the wrong place, a rotation skipped because the person who knew how is on leave. Automate creation, distribution, overlap and revocation with your secrets manager or a scheduled job, and log every rotation event. Many cloud providers and secrets managers support scheduled rotation or credentials that expire on their own.

Plan for emergency rotation

When a key may be compromised, speed matters more than elegance. Write down in advance how to revoke and replace each critical key, who has permission to do it, which systems need the new key and who has to be told. Practise it once, so the first time is not during an incident.

Legacy systems

Older systems may read keys from files at startup, accept only one key at a time or lack any automation hooks. A phased approach works: put a proxy or gateway in front of them that holds the real credential, wrap them with scripts that handle rotation, and replace them over time. Do not let one legacy system become the reason every key in the organization stays static.

Limit the damage with rate limits

Rate limiting caps how many requests a key can make in a time window. It protects your backend from overload and denial of service, keeps pay-per-use costs predictable and, importantly for key management, limits how much an attacker can do with a stolen key before someone notices.

Common forms:

  • Request quotas per key per minute, hour or day.
  • Concurrency limits on simultaneous requests from one key.
  • Per endpoint limits, tighter for expensive or sensitive operations.
  • Tiers based on plan or trust level.
  • Graduated responses that escalate from warnings to throttling to blocking or revocation.

If you run an API, return a clear 429 Too Many Requests with headers that show the limit, the remaining requests and when the window resets, so clients can back off. Allow short bursts for legitimate spikes. If you consume an API, implement exponential backoff with jitter and cache responses to stay under the limits. API gateways such as Kong, cloud API managers and Cloudflare all offer rate limiting without custom code, and the OWASP API Security Project lists missing resource limits as a common API risk.

The trade-off is that limits that are too tight hurt legitimate high volume users and generate support requests. Set them from real usage data and revisit them as usage grows.

Monitor usage and detect anomalies

A valid key used by the wrong person looks like a valid request. The only way to catch that is to watch how each key behaves and notice when it changes.

Establish a baseline

Track, per key: request volume over time, endpoints used, data transferred, source IPs and regions, user agents and time of day. That gives you a picture of normal behaviour. For example, if a key typically makes about 100 requests per hour, a sudden jump to 10,000 is worth an alert.

Set thresholds and tune them

Alerts should fire on meaningful deviations: a volume spike, a new country, calls to endpoints the key has never used, activity at unusual hours, a burst of authentication failures. Expect to tune them. A marketing campaign or a product launch can produce a legitimate spike, so knowing your business calendar makes alerts more reliable. Too many false positives and the team stops reading them.

Start simple with rule-based checks on your most sensitive keys and endpoints, then add statistical or machine learning detection once you have history to learn from. Correlate API signals with other security data, such as login events and deploys, for context.

Respond automatically where it is safe

For clear-cut cases, act without waiting for a human: throttle a key that exceeds its limit, require additional verification, or suspend a key that suddenly calls from an unexpected network. Use tiered responses (alert, then restrict, then block) so a false positive does not take down a legitimate integration.

Keep audit trails

Log every lifecycle event (creation, scope change, rotation, revocation) and enough request metadata to reconstruct what a key did. Audit trails support compliance reviews and are essential when you investigate an incident and need to know exactly what a leaked key accessed. Never log the key itself; log its ID or prefix.

Make it visible

Dashboards that show usage per key, recent alerts and keys nearing expiry turn raw logs into something a team will look at. Monitoring also surfaces unused keys, which are free to revoke.

Tools that help include AWS CloudTrail with GuardDuty, Google Cloud Security Command Center, Datadog, Splunk and the Elastic Stack, as well as the analytics built into most API gateways.

Manage the full key lifecycle

Rotation is one stage of a longer life. Treat keys as managed assets from request to retirement:

  1. Request and approval. A key is created for a stated purpose and owner, with an approval step for sensitive scopes.
  2. Issue. The key is generated with metadata, scopes and an expiry, and delivered straight into a secrets manager.
  3. Track. A central inventory lists every active key, its owner, purpose, environment, scopes, last use and expiry.
  4. Review. Owners confirm on a schedule that each key is still needed and still correctly scoped.
  5. Rotate. Keys are replaced on schedule or on demand.
  6. Revoke. Keys are retired when their purpose ends, their owner leaves or their expiry passes.

The inventory is the piece most teams lack. Without it you cannot answer basic questions in an incident: how many keys exist, who owns this one, what breaks if we revoke it. Build lifecycle steps into existing processes, especially developer onboarding and offboarding, so keys tied to a departing employee or retired service do not linger as orphaned credentials. Documented lifecycle processes also make compliance reporting for standards such as ISO 27001 and SOC 2 much simpler.

The costs are discipline and some administrative overhead. Keep the process light for low risk keys and strict for sensitive ones, so it does not slow development more than it needs to.

Build a system that scales

A handful of keys can be managed by hand. Hundreds across many services and clouds cannot. At that point architecture matters.

Centralized or distributed

Approach Strengths Weaknesses Best for
Centralized (one gateway or key service) Consistent policies, one place to audit, simpler to start Potential single point of failure, can become a bottleneck Smaller organizations and simpler setups
Distributed (each platform or team manages its own) No single outage stops everything, teams move independently Harder to keep policies consistent, harder to get a full inventory Large organizations with diverse platforms

Many organizations end up with a hybrid: one policy and one inventory, enforced by several systems. If you centralize, invest in redundancy and failover. If you distribute, invest in shared standards and a common inventory.

Integrate with identity

Connect key management to your identity provider (for example an OAuth 2.0 or OIDC based system such as Okta). Linking keys to real user and service identities simplifies access control, makes audit trails meaningful and lets offboarding revoke a person's keys along with their accounts. Where possible, prefer workload identity (cloud roles, service accounts, OIDC federation from CI) over static keys altogether; a credential that is issued on demand and expires on its own is one you never have to rotate.

Multiple environments and clouds

Applications often span development, staging and production across providers such as AWS and Azure. Keep keys environment specific, use each platform's native secret store or one secrets manager that spans them, and drive the configuration from infrastructure as code so the rules are identical everywhere.

Choose tooling that fits your size and constraints. A small team does well with a cloud secrets manager and good habits. A large enterprise with strict compliance needs inventory, approval workflows and automated reviews.

Train developers and catch leaks before they ship

Human error causes a large share of key leaks: a key pasted into a test file, a .env committed by accident, a key shared in a chat channel. Tools and habits catch most of it.

  • Write the rules down. A short internal page on how keys are requested, stored, used and rotated, with secure code examples for common cases, so nobody has to improvise.
  • Scan before commit. Pre-commit hooks with tools such as gitleaks or detect-secrets block commits that contain secrets.
  • Scan the repository. GitHub secret scanning and services such as GitGuardian detect known key formats in pushes and history; GitHub's push protection can block a push that contains a recognized secret.
  • Check images and artifacts. Keys also leak through Docker images, build logs and packaged bundles.
  • Teach with real cases. Short, regular training based on real incidents sticks better than a one-off policy document.
  • Make the right path easy. If fetching a secret from the vault is one line of code, people will use it.

This takes ongoing investment and may slow teams slightly at first, but it is far cheaper than responding to exposed credentials.

What to do when a key leaks

Assume it will happen eventually and have the steps ready.

  1. Revoke or rotate immediately. Do not wait to confirm abuse. Issue a new key, deploy it and disable the old one. If the key is in a public repository, assume it has already been found.
  2. Check what it did. Use audit logs and provider dashboards to see every request made with the key since the leak, including data accessed and charges incurred.
  3. Contain the impact. Reverse fraudulent actions where possible, block suspicious IPs and tighten rate limits on related keys.
  4. Remove the source. Delete the key from the file, chat or ticket where it leaked. For git, rewriting history helps hygiene but does not replace rotation.
  5. Notify. Tell the key owner, security team, affected customers and, where required, regulators.
  6. Fix the cause. Add the scanner, scope, hook or process change that would have prevented it, and record what you learned.

Many providers take part in GitHub's secret scanning partner program and may revoke or flag their keys when they appear in public repositories, but do not rely on that as your only safety net.

API keys for AI agents and MCP servers

AI coding agents and assistants add a new kind of key holder. When an agent in Cursor, Claude Code or a CLI calls external tools, it needs credentials, and those credentials end up in config files that are easy to commit or share.

The same rules apply, with a few specifics:

  • Prefer OAuth where the client supports it. Chat apps such as Claude and ChatGPT connect to remote MCP servers through an OAuth sign-in, so no long-lived key sits in a config file.
  • Keep editor and CLI keys out of project files. If an MCP config in your repository needs a key, reference an environment variable instead of pasting the value, and keep personal config files out of git.
  • One key per client. Give each editor or machine its own key, so you can revoke one without breaking the others.
  • Watch what agents do. Agents can call tools in loops. Usage limits and per-key visibility matter even more than for human driven code.

As an example, MultitaskAI is a remote MCP server that gives agents 166 exact tools, from DNS, WHOIS and SSL lookups to JSON repair and regex testing. Connectors in Claude and ChatGPT sign in with OAuth, while editors and CLIs such as Cursor, VS Code, Claude Code and Codex CLI use an API key you create in your account and can revoke at any time. Every signed-in account gets 100 free requests a day. The setup docs show how to add the key per client, and the tools list shows what an agent can call.

API key management checklist

Use this as a quick audit of your current keys.

Practice What to check Effort
Storage No keys in code, repositories, client bundles or URLs; keys live in a secrets manager Moderate
Generation Issued keys use a secure random source, a prefix and are stored hashed Low
Encryption TLS on every request; keys encrypted at rest, ideally with envelope encryption Moderate
Transport Keys in headers; logs redact credentials; signing or mTLS for sensitive traffic Moderate
Least privilege Each key has the minimum scopes and one consumer Moderate to high
Environments Separate keys and stores per environment; network or IP restrictions where possible Moderate
Rotation Expiry dates on every key; automated rotation with overlap; emergency runbook High
Rate limits Per key quotas and clear 429 responses Low to moderate
Monitoring Baselines, alerts, dashboards and audit logs per key High
Lifecycle Central inventory with owners; regular reviews; offboarding revokes keys Moderate
Developer practices Pre-commit hooks, repository scanning, documented standards, training Low to moderate

You do not need all of this on day one. Start with the high risk items (no keys in code, URLs or clients; least privilege; a way to rotate quickly), then add monitoring, lifecycle management and automation as the number of keys grows.

Frequently asked questions

How often should API keys be rotated?

It depends on what the key protects. Many teams rotate sensitive production keys every 30 to 90 days and lower risk keys every 6 to 12 months, and every key immediately after a suspected exposure. Automated rotation with an overlap period makes shorter intervals practical.

Are environment variables safe enough for API keys?

They are much better than hardcoding and fine for small projects and local development. For production systems with many services, a secrets manager adds access control, audit logs, versioning and rotation that environment variables lack.

Can I put an API key in frontend code?

Only if the provider designed it as a publishable key for client use. Secret keys in a browser or mobile app can always be extracted, so route those calls through your own backend.

What is the difference between an API key and an OAuth token?

An API key usually identifies an application and is long lived. An OAuth access token is issued for a specific user or client, carries scopes and expires quickly, and is obtained through a sign-in or token exchange flow. Many systems use a key or client secret only to obtain short-lived tokens.

What should I do first if I find a leaked key?

Revoke or rotate it immediately, then review its usage logs to see what it accessed, contain any damage and fix the cause of the leak.

Give your agent 433 tools in a minute

Connect MultitaskAI to your MCP client and ask in plain words. 100 requests a day are free.