API Secret Best Practices
A practical guide to protecting API secrets with secure generation, environment variables, secret managers, rotation, least privilege, and safe handling.
API secrets are credentials that allow software to authenticate to services and access protected resources. They can include API keys, client secrets, private tokens, signing secrets, database credentials, and other values that must remain confidential.
A leaked API secret can allow unauthorized users to access APIs, consume paid resources, retrieve private data, modify application state, or impersonate an application. Protecting secrets therefore requires more than simply hiding them in source code. Secure generation, storage, access control, rotation, monitoring, and safe deployment practices all matter.
API Secret Security Rules at a Glance
| Rule | Why It Matters |
|---|---|
| Generate secrets securely | Prevents predictable credentials |
| Never commit secrets to source control | Git history can preserve exposed credentials |
| Keep secrets out of client-side code | Browser code is visible to users |
| Use environment variables or a secret manager | Separates credentials from application code |
| Use least privilege | Limits damage if a secret is compromised |
| Rotate secrets regularly and after exposure | Reduces the useful lifetime of compromised credentials |
| Do not log secrets | Logs may be widely accessible |
| Mask secrets in interfaces | Reduces accidental disclosure |
| Use different secrets per environment | Limits development and production exposure |
| Monitor secret usage | Helps detect unauthorized activity |
What Is an API Secret?
An API secret is any confidential value used by an application or service to prove its identity or authorize access. The exact terminology differs between systems, but the security principle is the same: if possession of the value grants access, the value must be treated as a credential.
- API keys.
- API client secrets.
- OAuth client secrets.
- Webhook signing secrets.
- Service-account credentials.
- Private access tokens.
- Encryption keys.
- Database passwords.
- Application signing secrets.
API Key vs API Secret
The terms API key and API secret are sometimes used interchangeably, but they can represent different credentials. An API key may identify an application or account, while a secret may provide additional proof that the caller is authorized.
Regardless of the naming convention, any credential that grants access or helps authenticate a privileged request should be handled as sensitive information.
1. Generate Secrets with Secure Randomness
API secrets should be generated using a cryptographically secure random number generator. Conventional pseudorandom generators designed for simulations or games should not be used to create credentials that attackers must not be able to predict.
Cryptographically secure entropy
↓
CSPRNG
↓
Random bytes
↓
Encoded API secretThe security of a generated secret depends on the unpredictability of its underlying random data. Making a secret longer does not compensate for a predictable generation process.
2. Do Not Generate Secrets from Predictable Values
Timestamps, usernames, project names, server IDs, sequential counters, and similar values should not be used as the primary source for API secret generation. These values are often discoverable or guessable.
Bad:
timestamp + username + project ID
↓
predictable secret
Better:
secure random bytes
↓
unpredictable secret3. Use Sufficient Entropy
A secret needs enough effective entropy to make guessing infeasible. Entropy represents the amount of uncertainty in the generated value.
Possible values = 2^bits
128 bits → 2^128 possible values
256 bits → 2^256 possible valuesThe appropriate size depends on the credential's purpose, threat model, and the service's design. For many application-generated secrets, using a sufficiently large value from a trusted CSPRNG provides a very large search space.
4. Never Put API Secrets in Source Code
Hardcoding secrets directly into application source code is one of the most common credential-management mistakes.
// Avoid
const apiSecret = "super-secret-value";Source code is frequently copied, reviewed, backed up, published, scanned, and stored in Git repositories. Even if a secret is removed from the latest version, it may remain in Git history or another developer's local clone.
5. Use Environment Variables Carefully
Environment variables are a common way to provide secrets to server-side applications without placing them directly in source code.
API_SECRET=your-secret-value
DATABASE_PASSWORD=your-database-passwordEnvironment variables reduce the risk of accidentally committing secrets into source control, but they are not automatically a complete secret-management system. Access to the process environment can still expose sensitive values.
6. Never Expose Server Secrets to the Browser
A secret embedded in browser JavaScript is not secret. Users can inspect downloaded JavaScript, network requests, browser storage, and other client-side resources.
Server-side secret
↓
Server
↓
Authenticated API request
Do not:
Secret
↓
Browser bundle
↓
Anyone can inspect itIf a third-party API requires a secret credential, keep that credential on the server and proxy or mediate requests through a controlled backend when the architecture permits it.
7. Be Careful with Framework Environment Variables
Modern web frameworks often distinguish between server-only environment variables and variables intentionally exposed to client-side code. Developers should understand the framework's public-variable conventions before placing credentials into environment configuration.
8. Keep Secrets Out of Git
Environment files containing secrets should generally be excluded from source control when they contain real credentials.
.env
.env.local
.env.production.localA repository can safely contain an example configuration file with placeholder values while keeping actual credentials outside the repository.
.env.example
API_SECRET=
DATABASE_URL=
SERVICE_TOKEN=9. Git History Can Preserve Leaked Secrets
Deleting a secret from the current file does not necessarily remove it from Git history. Previous commits may still contain the credential, and anyone with access to the repository may be able to retrieve it.
If a real secret is committed, treat it as exposed. Removing the line from the latest commit is not enough. The credential should be revoked or rotated, followed by appropriate repository cleanup when necessary.
10. Use Secret Managers for Production
For production systems, a dedicated secret-management solution can provide stronger controls than storing credentials in ordinary configuration files. Secret managers can support encryption at rest, access policies, auditing, rotation, and controlled retrieval.
- Centralized secret storage.
- Fine-grained access control.
- Audit trails.
- Secret versioning.
- Automated or assisted rotation.
- Controlled application access.
- Reduced exposure in deployment files.
11. Follow the Principle of Least Privilege
An API secret should have only the permissions required for its intended task. If a credential only needs to read data, it should not automatically have permission to delete records or modify account settings.
Application
↓
Read-only credential
↓
Read-only API access
instead of
Application
↓
Administrator credential
↓
Full access12. Use Separate Secrets for Development and Production
Development, staging, testing, and production environments should not normally share the same credentials. If a development machine or repository is compromised, separate credentials limit the potential impact.
| Environment | Recommended Credential |
|---|---|
| Local development | Development-only secret |
| Testing | Dedicated test credential |
| Staging | Staging credential |
| Production | Production-only credential |
13. Rotate Secrets
Secret rotation means replacing an existing credential with a new one. Rotation limits the period during which a leaked credential remains useful.
Rotation policies should consider the sensitivity of the credential, how frequently it is used, whether automatic rotation is possible, and how quickly a compromised secret can be revoked.
14. Rotate Immediately After Exposure
If an API secret appears in a public repository, log, screenshot, issue tracker, chat message, or other location where unauthorized people could access it, assume it has been compromised.
Secret exposed
↓
Revoke old secret
↓
Generate new secret
↓
Update application
↓
Verify service
↓
Investigate exposure15. Avoid Logging Secrets
Secrets should not appear in application logs, debugging output, error messages, analytics events, or monitoring metadata. Logs are often retained for long periods and may be accessible to more people than the application itself.
Bad:
Authorization: Bearer abc123-secret-value
Better:
Authorization: Bearer [REDACTED]16. Mask Secrets in User Interfaces
Administrative dashboards and configuration interfaces should avoid displaying complete secrets by default. Masking reduces the chance of accidental exposure through screen sharing, screenshots, browser history, or shoulder surfing.
sk_live_********************7x2PA masked display is useful for identifying which credential is being viewed without unnecessarily revealing the entire secret.
17. Do Not Treat Masking as Encryption
Masking changes how a secret is displayed. It does not protect the underlying value in storage or memory. A masked value is therefore not a replacement for encryption, access control, or proper secret management.
18. Encrypt Secrets at Rest
Sensitive credentials should be protected when stored. Depending on the architecture, this may involve encrypted secret-management systems, encrypted databases, operating-system protections, or other appropriate controls.
Encryption at rest is one layer of defense. Applications still need access controls because a running process must eventually obtain the plaintext credential to use it.
19. Understand dotenv Files
dotenv files are convenient configuration files commonly used during application development. They can contain sensitive values, so production teams should establish clear rules about where these files are stored, who can access them, and whether encrypted configuration is more appropriate.
.env.example → safe placeholders
.env → may contain secrets
.env.local → local sensitive configuration20. Encrypt Sensitive Configuration When Appropriate
Encrypted environment files can be useful when configuration needs to travel through deployment workflows or repositories while remaining unreadable without an appropriate decryption mechanism.
Encryption does not remove the need for access control. The encryption key itself becomes sensitive and must be protected separately.
21. Do Not Put Secrets in URLs
Credentials placed in URLs can leak through browser history, proxy logs, analytics systems, server logs, referrer information, screenshots, and monitoring tools.
Avoid:
https://api.example.com/data?api_key=SECRET
Prefer:
Authorization header
or another documented secure authentication mechanism22. Protect Secrets in CI/CD
Continuous integration and deployment systems frequently need access to credentials. Secrets should be stored using the platform's protected secret mechanism rather than hardcoded into workflow files.
- Use protected CI/CD secret storage.
- Restrict which jobs can access production credentials.
- Avoid printing secret values in build logs.
- Use separate credentials for different environments.
- Rotate credentials when a runner or environment may have been compromised.
23. Protect Build and Deployment Logs
A secret can leak even when it is not explicitly printed. Commands, environment dumps, failed deployment messages, stack traces, and debugging tools can accidentally expose sensitive variables.
24. Do Not Send Secrets to Third-Party Analytics
Analytics and telemetry systems should not receive API keys, access tokens, passwords, private credentials, or other secrets. Be especially careful when logging complete request URLs, headers, request bodies, and environment configuration.
25. Monitor API Secret Usage
Where supported, API providers should provide usage records, authentication events, IP information, timestamps, scopes, or other signals that help identify suspicious activity.
- Unexpected geographic locations.
- Unexpected IP addresses.
- Unusual request volume.
- Unexpected API endpoints.
- Sudden increases in paid usage.
- Requests from previously unseen environments.
26. Make Revocation Easy
A secure secret-management system should make it possible to revoke a credential quickly. If a secret cannot be disabled without a lengthy manual process, teams may delay responding to an exposure.
Applications should ideally support replacing credentials without requiring a full redesign or lengthy outage.
27. Support Secret Rotation Without Downtime
Applications can sometimes support overlapping credentials during rotation. The new secret is deployed first, the application switches to it, and the old credential is revoked after confirming that no required systems still depend on it.
Old secret ──────────────┐
│
New secret ──────────────┤
↓
Deploy
↓
Verify traffic
↓
Revoke old secret28. Avoid Sharing One Secret Across Many Applications
Using the same credential across multiple applications increases the blast radius of a compromise. If one application is breached, attackers may gain access to every service that accepts the shared credential.
Where practical, issue separate credentials to separate applications, services, environments, and workloads.
29. Protect Webhook Signing Secrets
Webhook signing secrets are used by services to verify that incoming requests were generated by a trusted provider. They should be treated like other API credentials and stored securely.
Applications should verify signatures according to the provider's documented protocol and avoid logging complete signature secrets or sensitive request credentials.
30. Separate Public Configuration from Secrets
Not every configuration value is secret. API base URLs, feature flags, public identifiers, and client-side configuration may be intentionally visible. Confusing public configuration with secrets can lead either to unnecessary restrictions or accidental credential exposure.
| Value | Usually Secret? |
|---|---|
| API base URL | Usually no |
| Public application ID | Depends on the service |
| API key with privileged access | Yes |
| Client secret | Yes |
| Database password | Yes |
| Webhook signing secret | Yes |
31. Secret Names Should Not Reveal the Secret
Environment variable names such as STRIPE_SECRET_KEY or DATABASE_PASSWORD identify the purpose of a credential without exposing its value. The name itself is not normally the sensitive part; the secret value is.
STRIPE_SECRET_KEY=...
DATABASE_PASSWORD=...
PAYMENT_SERVICE_TOKEN=...32. Beware of Error Messages
Errors can accidentally reveal credentials through request dumps, configuration objects, authorization headers, or connection strings. Production error handling should redact sensitive values before sending information to logs or monitoring services.
33. Do Not Put Secrets in Screenshots
Screenshots of dashboards, terminal sessions, configuration files, and deployment interfaces can accidentally expose credentials. Before sharing technical screenshots, inspect them for API keys, tokens, passwords, cookies, private URLs, and environment variables.
34. What to Do After a Secret Leak
1. Assume the secret is compromised.
2. Revoke or disable it.
3. Generate a replacement.
4. Deploy the replacement securely.
5. Check logs and usage for abuse.
6. Remove the exposed credential from visible sources.
7. Review Git history if applicable.
8. Investigate how the exposure happened.
9. Improve controls to prevent recurrence.The first priority is revocation. Cleaning up the repository or deleting a message does not make an already exposed secret trustworthy again.
API Secret Checklist for Developers
☐ Generated using a CSPRNG
☐ Sufficiently long and unpredictable
☐ Never hardcoded in source code
☐ Not committed to Git
☐ Not exposed to browser code
☐ Stored using appropriate secret management
☐ Different between environments
☐ Limited to required permissions
☐ Not written to logs
☐ Masked in administrative interfaces
☐ Rotatable
☐ Revocable
☐ Monitored for suspicious use
☐ Protected in CI/CD
☐ Replaced immediately after exposureCommon API Secret Mistakes
- Hardcoding an API key in JavaScript.
- Committing .env files containing production secrets.
- Using the same secret in development and production.
- Generating credentials with predictable randomness.
- Putting secrets into URLs.
- Printing environment variables during debugging.
- Logging Authorization headers.
- Using an administrator credential for a simple API task.
- Never rotating long-lived credentials.
- Failing to revoke a leaked secret.
- Sharing one credential across multiple applications.
- Assuming masking provides real cryptographic protection.
Frequently Asked Questions
What is an API secret?
An API secret is a confidential credential used to authenticate or authorize access to an API or protected resource. Examples include API keys, client secrets, private tokens, and signing secrets.
Where should API secrets be stored?
API secrets should be stored in protected environment variables or, preferably for production systems, a dedicated secret-management system. They should never be embedded directly in source code.
Can an API secret be stored in frontend JavaScript?
No, not if the value must remain secret. Anything delivered to a browser can potentially be inspected by users. Sensitive credentials should remain on trusted server-side infrastructure.
How should API secrets be generated?
API secrets should be generated using a cryptographically secure random number generator with enough unpredictable data to meet the credential's security requirements.
What should I do if an API key is committed to Git?
Treat the key as compromised and revoke or rotate it immediately. Then remove the secret from the repository where appropriate and investigate whether it may have been accessed or misused.
Should API secrets be logged?
No. API secrets should be excluded or redacted from application logs, error reports, analytics, monitoring systems, and debugging output.
Why should different environments use different API secrets?
Using separate credentials for development, testing, and production limits the impact of a compromised credential and makes access easier to revoke and audit.
What is the best response to a leaked API secret?
Immediately revoke or disable the exposed credential, generate a replacement, deploy it securely, investigate possible misuse, and fix the source of the leak to prevent it from happening again.
Useful API Secret Tools
The Secret Generator can create random secret values, while API Key Generator is useful for generating API-style credentials. Environment Variable Generator can help prepare configuration values, dotenv Encryptor can help protect dotenv-based configuration, and Secret Mask Generator can create masked representations suitable for interfaces and logs.
Conclusion
API secret security is a lifecycle rather than a single configuration choice. A secure secret should be generated unpredictably, stored appropriately, kept away from client-side code and source control, restricted to the permissions it actually needs, monitored, rotated, and revoked when exposure is suspected.
The most important principle is to treat every credential that grants access as a real secret. Keeping it out of Git is only the beginning. Strong generation, proper storage, least privilege, secure deployment, careful logging, and rapid incident response together provide much stronger protection for APIs and the applications that depend on them.