Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

API Key Security: Safe Storage, Access & Rotation

· 5 min read · Home Security

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to store, access, and rotate API keys securely. You'll learn practical steps to prevent leaks, limit damage if a key is exposed, and keep your applications running smoothly. By the end, you'll have a clear process for managing keys across development, testing, and production environments.

What You'll Need

  • Access to your API provider's dashboard (where keys are issued)
  • A secret management tool (e.g., AWS Secrets Manager, HashiCorp Vault, or a local tool like `pass`)
  • Basic familiarity with your operating system's terminal/command line
  • Your application's deployment environment (cloud platform, server, or container)

Step-by-Step

  1. Identify all API keys in use. List every service that requires an API key: payment gateways, cloud providers, email services, databases, etc. Note where each key is currently stored (environment variables, config files, code, etc.).
  2. Choose a secret manager. For cloud-based apps, use the provider's native service (e.g., AWS Secrets Manager, Azure Key Vault, GCP Secret Manager). For smaller projects or local development, use a tool like `pass` or `sops`. Avoid storing keys in plain text files or version control.
  3. Move keys out of code and config files. Replace hardcoded keys with references to your secret manager. For example, in a Node.js app, use `process.env.STRIPE_API_KEY` instead of `const key = "sk_live_..."`. In Python, use `os.environ.get("STRIPE_API_KEY")`.
  4. Set environment variables properly. In development, use a `.env` file that is NOT committed to version control (add it to `.gitignore`). In production, set environment variables via your hosting platform's dashboard or deployment script—never in code.
  5. Restrict access to keys. In your secret manager, grant access only to the services and team members that absolutely need it. Use IAM roles or service accounts instead of sharing a single key across multiple applications.
  6. Encrypt keys in transit and at rest. Ensure your secret manager encrypts data by default. Use HTTPS for all API calls. Never transmit keys over unencrypted channels like email or plain HTTP.
  7. Implement key rotation. Set a rotation schedule (e.g., every 90 days) or rotate immediately if a key is suspected of being exposed. Most providers allow you to generate a new key and deactivate the old one. Update your secret manager with the new key, then test your application.
  8. Automate rotation where possible. Many cloud secret managers offer automatic rotation for certain services (e.g., AWS Secrets Manager can rotate RDS credentials). Enable this to reduce manual effort and human error.
  9. Monitor key usage. Enable logging and alerts for API key usage. Watch for unusual patterns like requests from unexpected IPs or a sudden spike in traffic. Set up alerts to notify your team of potential breaches.
  10. Document your process. Write down where keys are stored, who has access, rotation schedule, and emergency procedures. Keep this document in a shared, secure location (e.g., internal wiki) so team members know what to do.

Common Mistakes

  • Committing keys to version control. Even if you remove them later, they remain in git history. Use tools like `git-secrets` or `trufflehog` to scan for accidental commits.
  • Using the same key for development and production. This increases risk if a dev environment is compromised. Use separate keys per environment.
  • Storing keys in client-side code. Anything in JavaScript, mobile apps, or desktop apps can be extracted. Only use server-side code to call APIs with keys.
  • Sharing keys via chat or email. These are often stored insecurely and can be intercepted. Use a secret manager to share access instead.
  • Forgetting to revoke old keys after rotation. If you don't deactivate the old key, it remains a security hole. Always revoke immediately after switching.

Tips

  • Use short-lived keys where possible. Some providers offer temporary credentials (e.g., AWS STS) that expire automatically, reducing the impact of a leak.
  • Prefix keys with a recognizable identifier. For example, `sk_live_` vs `sk_test_` helps quickly identify the environment.
  • Rotate keys in a staggered manner. If you have multiple services using the same key, rotate one at a time to avoid downtime.
  • Use a dedicated service account for each application. This allows you to revoke access for one app without affecting others.
  • Test your rotation process. Do a dry run in a staging environment to ensure your application handles key changes gracefully.

Troubleshooting

  • Application fails after rotation. Check that the new key is correctly set in your secret manager and that your application is fetching it at runtime. Ensure the key is active and has the correct permissions.
  • Key not found in environment variables. Verify that the `.env` file is in the correct location and that your application loads it (e.g., using `dotenv` in Node.js). In production, confirm the environment variable is set in the hosting platform's settings.
  • Permission denied errors. Your service account or IAM role may not have access to the secret. Check the secret manager's policy and grant the necessary permissions.
  • Rate limiting or quota issues. If you rotate keys frequently, you might hit provider limits on key generation. Wait or contact support if necessary.
  • Accidental commit of a key. Immediately revoke the key, remove it from the repository, and rewrite git history if the repo is public. Use tools like `git filter-repo` to purge it.

Frequently Asked Questions

Can I store API keys in a database?

It's better to use a dedicated secret manager, but if you must, encrypt the keys before storing them in a database and restrict access to that table.

How often should I rotate API keys?

At least every 90 days, or immediately if a key is exposed. Some providers offer automatic rotation; use it when possible.

What's the difference between an API key and a secret?

An API key is a type of secret used to authenticate API requests. Secrets can also include passwords, tokens, and certificates.

Is it safe to use environment variables?

Yes, environment variables are safer than hardcoding, but they can still be exposed in logs or via debugging. Use them in conjunction with a secret manager for production.

What do I do if my key is leaked?

Revoke the key immediately, generate a new one, update your applications, and investigate how the leak occurred to prevent future incidents.

Can I use a single key for multiple services?

It's not recommended. If one service is compromised, all others are at risk. Use separate keys per service or application.