- Binh Bui
Photo by Kristina Flour
Storing and managing secrets like API keys and other credentials can be challenging. Your API key is valuable information and an accidental leak could result in unwanted calls, app blockage, or worse. Publicly exposing your API keys can lead to unexpected charges on your account.
As a developer, API Keys are typically issued to you to identify the project you are working on and to enforce rate and access limits on proper API usage. These API keys are typically just static secrets baked into your app or web page, and they are pretty easy to steal but painful to replace. You can do better.
Managing API Keys
[x] Using separate API keys for each app, environment, and service.
This limits the scope of each key. If an API key is compromised, you can delete or regenerate the impacted key without needing to update your other API keys.
[x] Monitoring your API usage
Monitoring your API usage to detect unauthorized usage is a good idea.
[x] Applying API key restrictions
By adding restrictions, you can reduce the impact of a compromised API key on your application. Based on the API provider, you can restrict the API key to a specific app, environment, or service.
- You can restrict the API key to a specific app, environment, or service.
- You can also restrict the API key to a specific region.
- You can also restrict the API key to a specific IP address.
- You can also restrict the API key to a specific user.
[x] Restrict API access permissions
Add default to minimal permission scope for APIs. Choose right scope for each API.
[x] Delete unneeded API keys to minimize exposure to attacks.
[x] Generate a new key if you suspect a compromise
Store secrets safely
[x] Don’t store your API key directly in your code.
Don’t expose your API key or secret in your code. Instead, use a library to manage your API keys. For example, you can use Node.js’s
dotenv to store your API key and secret in a file called
.env in the root of your project. This file is ignored by Git, so it is safe to store your API key and secret in this file.
[x] Use local environment variables, when feasible
When you are working on a local environment, you can use local environment variables to store your API key and secret. This is a good idea because it reduces the risk of your API key and secret being exposed to your code. Example of a local environment variable:
export API_KEY=<your-api-key> export API_SECRET=<your-api-secret>
[x] Consider using an API secret management service
Secret management services are a great way to manage your API keys and secrets. They are a great way to manage your API keys and secrets. One solution for convenience and peace of mind is to use a secret management service like AWS Secret Manager.