API Key and Secret Token Security Guide
API key security: the risk of hardcoded keys, storing secrets in .env files and vaults, rotation, responding to a leak and generating tokens with a CSPRNG.
API keys and secret tokens are among the most critical and most neglected parts of modern software. A user who forgets a password can reset it; a leaked API key can run up bills, pull data or lock a system overnight. This guide covers how to generate, store, rotate and respond to leaks of application secrets.
What Is an API Key or Secret Token?
An API key is a long random string an application uses to prove its identity to another service. "Secret" is the broader family: webhook signing keys, database connection strings, service account credentials, JWT signing keys and TLS private keys all belong to it.
The key difference from a human password: an API key is stored, not memorised. A person picks something memorable; an application uses a 32–64 character fully random string. The risks are therefore different. With human passwords the problem is guessability; with machine secrets it is generation, storage and rotation.
The Biggest Hole: Hardcoded Keys
The most common source of leaked keys is writing them straight into source code:
const API_KEY = "sk-live-9f2b7c..."; // never do this
This is dangerous for three reasons:
- Git history does not forget. Removing the key in a later commit leaves it in every earlier version; anyone who clones the repository can read old commits.
- Public repositories are scanned. Automated scanners constantly crawl public GitHub repositories looking for key patterns. Assume any key pushed by mistake has leaked.
- The key travels with the code. It can be extracted from mobile app packages, found in Docker image layers, read in client-side JavaScript, and left behind in error messages and logs.
The rule is simple: once a key has entered source code, it is no longer secret. The same applies to committing a .env file that was never added to .gitignore.
Storing Secrets Safely: .env Files and Vaults
| Method | Good for | Limits |
|---|---|---|
.env + .gitignore |
A single developer's local setup | Distributed by hand, no audit trail |
| CI/CD secret variables | Build and deploy pipelines | Available only inside the pipeline |
| Secret manager (Vault, AWS Secrets Manager, Azure Key Vault, Google Secret Manager) | Teams and production | Needs setup; the strongest option |
Practical tips:
- Commit only a
.env.examplefile that lists variable names with empty values. - Restrict the
.envfile's permissions (for example, readable by the owner only). - Use a central secret manager in production; access control, audit logs and automatic rotation are the real value.
- For small teams, the secret-sharing features of a team password manager are a reasonable intermediate step.
What Is Token Rotation and Why Does It Matter?
Rotation means replacing a key with a new one at intervals or after specific events. The goal is to shorten the window in which a leaked key is usable.
Typical triggers:
- Someone with access to the key leaves or changes role
- Suspicious entries in access logs
- Systems being migrated, reconfigured or handed to a contractor
- Contractual and compliance requirements
The standard zero-downtime pattern:
- Create the new key and register it with the service (the old key still works).
- Move every consuming service to the new key.
- Confirm from the logs when the old key was last used.
- Revoke the old key and record the change.
There is no universal rotation interval; it depends on risk, the sensitivity of the data the key reaches and the provider's policy. What matters is that rotation is a documented, repeatable process.
Emergency Plan for a Leaked API Key
- Revoke it. Revoke first, investigate second. An outage is almost always cheaper than a breach.
- Issue a new key and update the consuming services.
- Check for abuse. Review the provider's usage logs for unfamiliar IPs, sudden spikes and unauthorised operations.
- Clean the Git history with tools such as
git filter-repoor BFG Repo-Cleaner. This does not undo the leak; it only makes future discovery harder. The real fix is step 1. - Find the root cause. Was it a commit, a log, unauthorised access? Add leak scanners such as gitleaks or trufflehog as a pre-commit check.
- Notify if required. If the key could reach customer data, legal and ethical obligations apply.
Least Privilege
Even if a key leaks, the damage is limited to the permissions it has:
- Do not grant write access when read-only is enough.
- Scope the key to specific resources (one bucket, one service, one database).
- Add IP restrictions and an expiry date where possible.
- Use separate keys for development, test and production.
- Never use the root/admin account's key for routine work.
- List and delete unused keys regularly.
Generating Cryptographic Tokens
If the key itself is not random, careful storage is pointless:
- Use a CSPRNG. Predictable generators such as
Math.random()are not suitable; usecrypto.getRandomValuesin the browser and the operating system's cryptographic randomness on the server. - Aim for enough entropy. At least 128 bits for long-lived secrets; 256 bits is common practice. A UUID v4 carries about 122 random bits: fine as an identifier, but prefer a longer secret for signing keys.
- Do not truncate or transform the output. Use standard encodings such as Base64URL or hex rather than home-made schemes.
- Generate in a trusted environment. A token typed into a third-party website should no longer be considered safe.
To do this in your browser without sending anything to a server, use the Token Generator: it creates UUID v4, hex and Base64URL values locally.
Frequently Asked Questions
What is the difference between an API key and a password? A password proves a person's identity and is expected to be memorable; an API key proves an application's identity and is a long, random, stored string. For passwords the main risk is guessability; for keys it is storage and rotation.
I accidentally committed my .env file. What should I do?
Revoke the key first, then issue a new one and update your services. Cleaning the Git history afterwards is fine, but it does not undo the leak; revocation does.
How often should keys be rotated? There is no universal interval. Staff changes, suspicious activity and compliance requirements are the triggers. What matters is a documented rotation process you can run when needed.
Why is Math.random() not good enough for tokens?
It is not designed for cryptographic security; its output can be predictable and reproducible by an attacker. Tokens must come from a CSPRNG.
How do I know whether a leaked key was abused? Compare the provider's audit logs with your normal usage: look for unfamiliar IP addresses, unusual locations, sudden request spikes and calls to endpoints you never use.
A strong security chain starts with strong randomness. For human passwords use the Password Generator, which runs entirely in your browser, and check whether a password appears in breach lists with the breach checker.
Generate Strong Credentials Instantly
Hardware-backed Web Crypto API with zero logging and zero server contact.