API Key Security: How to Store, Send, and Rotate Keys14 min read2,818 words

API Key Security: How to Store, Send, and Rotate Keys

Learn what an API key actually proves, where to send and store it, how to limit and rotate access, and what to do when a key leaks.

API key securityAPI key managementstore API keysrotate API keysAPI key leak response
API Key Security: How to Store, Send, and Rotate Keys

API Keys Are App Passwords: How to Handle Them Safely

An API key is a string your application sends to a service so the provider can identify the caller and decide whether to accept the request. That's why they're useful for connecting software, tracking usage, and enforcing plan limits. But the key point is simple: it's a credential. If someone else gets that string, they may be able to use it as if they were your application.

The practical risk is easy to miss. A key that you accidentally paste into a repo, a browser bundle, a container config, or a log can keep working long after the original mistake. If the key has broad permissions, you can end up with unexpected usage, surprise charges, data exposure, or outages when you finally revoke it.

A safe setup isn't just "put the key in an environment variable." You also need to understand what the key proves, where it travels, what it allows, and how you'll replace it without breaking production. This guide covers those choices, with request examples, storage options, rotation steps, and a troubleshooting table you can use when an API call fails.

What an API key proves and what it does not

An API key is a credential tied to an application, project, or account. Your service includes it in a request. The provider then uses it to identify the caller and apply whatever rules are attached to that key. Stripe, for example, describes secret keys as account credentials (similar to a username and password). The key difference is that an API key usually represents software - not a specific person.

Here's the mental model that keeps people out of trouble: an API key is a password for a program. If someone has the value, they can often make requests with it. In most cases, the server can't tell whether the caller is your production service, a developer's laptop, or an attacker who copied the key. RFC 6750 talks about bearer tokens in this same "whoever possesses it can use it" way, and the practical concern carries over when an API key is accepted as a bearer credential.

It helps to split things teams often mash together:

Job What the server is checking Typical failure
Identification Which app, project or account made the call? Missing or unknown key
Authentication Is the credential valid and current? 401 Unauthorized
Authorization Is this credential allowed to do this action? 403 Forbidden
Rate limiting Is this caller exceeding its allowed request rate? 429 Too Many Requests

A valid key still doesn't mean the caller can do everything. Many providers support restricted keys, scopes, or project-level permissions. Use those controls so a credential's access matches what your application actually needs.

Also, an API key doesn't prove that a user is trustworthy, and it often doesn't tell you which user triggered a request. If you need user-level identity, delegated access, or permissions that change over time, don't try to force API keys to do that job. Use a design built for identity and authorization. OAuth access tokens, for example, can represent a grant with a defined scope and duration. API keys vary by provider and may not expire until you revoke them.

For a low-risk integration, a restricted API key can be straightforward. For systems that handle payments, personal data, or other high-value actions, don't rely on a broad, long-lived key as your only control. Use narrow permissions and pair it with user authentication, monitoring, and a rotation plan.

How to send an API key safely

Use the request format your API provider specifies. When the provider expects a bearer-style credential, the usual choice is the Authorization header:

GET /v1/things HTTP/1.1

Host: api.example.com

Authorization: Bearer YOUR_API_KEY

RFC 6750 is about OAuth bearer tokens, not API keys specifically, so your provider may require a different header name or format. Follow their docs. The general rule stays the same: send the credential over HTTPS and avoid putting it in the URL.

URLs get logged. You'll see them in server logs, browser history, proxy records, and monitoring tools. That's why query-string credentials like ?apiKey=YOUR_API_KEY are a bad idea. OWASP's REST security guidance warns against putting passwords, tokens, and API keys in URLs. If there's no alternative, understand where those URLs are recorded and what access controls protect the logs - and don't pretend a URL is a "private channel."

For a quick shell command, read the value from your current environment instead of pasting it directly into the command:

export API_KEY=YOUR_API_KEY

curl https://api.example.com/v1/things \

-H "Authorization: Bearer $API_KEY"

This helps avoid leaving the literal key in your command history or in a script you later commit. But it's not a full secrets-management solution: shell history, process configuration, or diagnostic output can still expose credentials depending on how you run things. For production workloads, use the environment or secrets service your deployment platform provides.

In Node.js, you can fail early when the key is missing, instead of sending a malformed request and chasing ghosts:

const apiKey = process.env.API_KEY

if (!apiKey) throw new Error('API_KEY is not set')

const res = await fetch('https://api.example.com/v1/things', {

headers: { Authorization: `Bearer ${apiKey}` },

})

if (!res.ok) throw new Error(`Request failed: ${res.status}`)

console.log(await res.json())

HTTPS is mandatory for protecting credentials in transit. A header doesn't automatically make the request safe if the connection isn't encrypted. Also make sure your app doesn't log authorization headers or dump full request configuration when errors happen - things can be handled correctly at the network layer and still leak through debug output.

Where to store API keys

Keep secret keys on the server. Don't put them in source code, and don't put them into anything delivered to a user's device. If a key is embedded in a browser or mobile app, it's not secret - users can inspect network traffic, unpack application files, or read the client bundle. If a provider offers a publishable or client-side key, use it only for the specific purpose and permissions they designed it for.

A practical storage hierarchy looks like this:

Location Recommendation Why it matters
Committed source code Never Repositories get scanned, copied, and sometimes exposed - including private ones
Browser or mobile client Never for secret keys The app can be inspected by its users
Email, chat or support ticket Never Messages get forwarded, searched, and retained beyond the task
Server environment variable Reasonable baseline Keeps the value out of the code repository and lets you inject it at runtime
Secrets manager or vault Preferred for production Centralizes access, supports auditing, and makes revocation easier
Dockerfile ENV or ARG Avoid Values can end up in image layers, build output, or config history

For a small service, a protected server environment variable can be a decent starting point. Still restrict who can view production configuration, avoid exposing variables in error pages, and keep diagnostic tools away from untrusted users. Environment variables are a delivery mechanism, not a guarantee that the secret is safe from every process or operator with access to the runtime.

As you add more services and more people, a secrets manager is usually the better fit. The app references the secret by name, and the platform injects the actual value at runtime. That separates the secret from application code and can give you an access audit trail. It also makes it easier to revoke or update a credential without editing a repository.

Keep staging and production keys separate. A test service shouldn't need production credentials, and a developer's local environment shouldn't inherit broad production access by default. If the provider supports it, give each integration its own key. If one service leaks a credential, separate keys limit how many systems you have to investigate and replace.

And add prevention where mistakes happen. A pre-commit secret scanner can block a credential before it lands in Git. Repository scanning can catch some secrets after they're committed. Neither replaces careful storage: scanners can miss unfamiliar formats, and keys can end up in logs, tickets, or client bundles even if nobody touched the repo.

How to rotate and respond to a leaked key

Rotation isn't just "security theater." It's also an operational test. A key that never changes gives you a long window for misuse if it escapes. Regular rotation shrinks that window, and practicing the process makes sure your team can actually execute it under pressure.

For routine rotation, use an overlap period so you don't turn maintenance into an outage:

  1. Create a replacement key with the same permissions (or narrower permissions if the app no longer needs the old access).
  2. Store the new value in your secrets manager or protected runtime configuration.
  3. Deploy the application and confirm requests work with the replacement.
  4. Check that every relevant service and background job has switched over.
  5. Revoke the old key only after you've verified the replacement is in use.

Revoke last during planned rotation. If you revoke first, anything still using the old value may fail all at once. Some providers offer key-expiry features, but expiry dates only help if someone owns the replacement work and monitors the schedule.

A leak is different. Treat a key as compromised if it shows up in a public repository, a log file, an email, a chat message, or a client bundle. You don't need proof that someone used it. Stripe recommends rotating exposed or compromised keys, and GitHub's secret-scanning guidance similarly prioritizes rotating the credential.

Use this incident sequence:

  1. Replace or revoke the exposed key immediately. If you can tolerate a short overlap and the risk is manageable, deploy the new key before revoking the old one. If active misuse is likely, revocation may have to come first, even if it risks downtime.
  2. Update every consumer. Change your deployment configuration or secrets manager values, then verify production jobs and services are using the replacement.
  3. Review usage logs. Look for odd request times, volumes, IP addresses, or user agents during the exposure window. Check for charges or data access that don't match expected activity.
  4. Remove the source of the leak. Fix the logging, deployment, repository workflow, or communication process that exposed the value. Otherwise, the replacement may leak through the same path again.
  5. Clean up repository history only if needed. Removing a secret from Git history can be slow and painful. Once the key is revoked, rewriting history isn't a substitute for responding to the credential and may not be necessary for containment.

Automated secret scanning helps with detection, not with incident response. GitHub documents scanning across repository content and alerts for supported secrets, but coverage and provider response vary. Assume a scanner can miss credentials. Your team still needs an owner, a way to revoke keys, and access to usage logs.

How to diagnose API key errors

An HTTP status code can point you toward the failing part of the request, but it's not a full diagnosis. Providers may use different response bodies, or they may hide resources from callers without permission. Check the key, endpoint, environment, and permissions as a group before changing code.

Symptom Likely cause What to check
400 Bad Request Malformed request, repeated credential or unsupported parameter placement Send the key once, in the provider's documented location
401 Unauthorized Missing, invalid, expired or revoked key Confirm the header name, value, environment and key status
401 soon after a leak The provider may have disabled an exposed key Replace the key and investigate where it appeared
403 Forbidden Key is valid but lacks permission for the operation Check its scope, role or restricted-key settings
404 Not Found for an expected resource The service may conceal resources from unauthorized callers Verify permissions and account/project context, then check the path
429 Too Many Requests Rate limit or plan limit reached Back off, review request volume and check the account's limits

A common mistake is treating 401 and 403 as if they mean the same thing. Broadly: 401 means the request didn't supply an acceptable authentication. 403 usually means the caller is authenticated but not allowed to do that action. Some providers use these codes differently, so read the response body and the provider's error docs before assuming the distinction is exact.

For a 401, check for a missing header, a copied value with whitespace, the wrong key for the current environment, or a key that has expired or been revoked. Don't print the full key while debugging. Log a safe identifier or a short, non-sensitive fingerprint if you need to correlate which configured credential got selected.

For a 403, creating yet another broad key is often the wrong first step. Figure out which permission the request actually needs, then grant only that capability. For a 429, retrying immediately in a tight loop can make things worse. Use backoff, follow any retry guidance in the response, and investigate whether a new usage pattern or a misconfigured job caused the spike.

A 404 can be deliberate. Some services return it instead of confirming that a resource exists but is inaccessible to the current credential. Confirm the project or account associated with the key, then check authorization before concluding the endpoint is wrong.

Key takeaways

  • Treat an API key as a password for an application: possession may be enough to use it.
  • Send it over HTTPS in the header format your provider expects. Avoid putting credentials in URLs.
  • Keep secret keys on the server. Start with a protected environment variable, and move to a secrets manager as your setup grows.
  • Give each service and environment its own key, with only the permissions it needs.
  • During planned rotation, deploy and verify the replacement before revoking the old key.
  • If a key leaks, replace or revoke it first, review usage, and then fix the place where it got exposed.

Conclusion

An API key is a simple way to identify and authorize an application, but that simplicity only works when you keep the credential under control. Store it server-side, send it over HTTPS in the provider's documented header format, and limit permissions to what the application actually needs.

The operational details matter just as much as where you store the value. Keep keys separate across environments, practice rotation before there's an emergency, and know where to check usage when something looks off. If a key leaks, contain it first, then investigate and fix the process that allowed it to escape.

Frequently Asked Questions

It is similar in the security sense: whoever possesses it may be able to use it. The difference is that an API key usually belongs to an application, project or account rather than a person. Treat it as a credential, keep it private and limit what it can do.
A protected server-side environment variable is a reasonable baseline and is safer than committing the key to source code. It is not automatically secure in every setup. Restrict access to runtime configuration, prevent secrets from appearing in logs, and consider a secrets manager for production workloads.
Do not embed a secret API key in a client application. Users can inspect browser bundles, network requests or mobile app files and extract it. Use a provider’s publishable key where available, or send client requests through a server that holds the secret.
Rotate or revoke it immediately, then update the applications that use it and review request logs for unexpected activity. Fix the source of exposure, such as a committed file or verbose log. Removing the value from repository history does not invalidate the credential.
For planned rotation, usually no. Create and deploy the replacement, verify that all services use it, and then revoke the old key. For an active leak or suspected misuse, immediate revocation may matter more than avoiding downtime; weigh the service impact against the exposure risk.

Related articles