Learn how to secure environment variables and API keys in Node.js applications. Step-by-step guide using dotenv, .env files, secret managers, and best practices for safe API key management
Managing environment variables and API keys securely is crucial in Node.js applications. If handled improperly, secrets like database passwords, API keys, and tokens may leak into version control, exposing your app to attackers.
This guide will walk you through best practices and coding steps to keep your secrets safe.
1. Why Environment Variable Security Matters
- API key leaks can give attackers access to your database, payment systems, or third-party services.
- Hardcoding credentials in your code means they could end up in GitHub repos.
- Exposed
.env
files make it easy for hackers to take control of your application.
Securing environment variables is not optional — it’s essential.
2. Use a .env
File and dotenv
Never hardcode secrets inside your code. Instead, store them in a .env
file.
Install dotenv
npm install dotenv
Example
PORT=3000
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/mydb
JWT_SECRET=mySuperSecretKey
API_KEY=12345-ABCDE
Load in your app
require('dotenv').config();
const express = require('express');
const app = express();
console.log('Server running on port:', process.env.PORT);
Important: Add .env
to your .gitignore
so it’s not committed.
3. Don’t Commit Secrets to GitHub
Add .env
and other sensitive files to .gitignore
:
# Environment variables
.env
*.env
4. Use Environment Variables in Production
Instead of .env
files in production, set secrets using your hosting provider:
Linux / macOS
export JWT_SECRET=myProductionSecretexport API_KEY=abcd12345
Node.js reads it directly
console.log(process.env.JWT_SECRET);
On cloud services (Heroku, Vercel, AWS, etc.), configure environment variables via their dashboards.
5. Encrypt Secrets with a Vault
For enterprise-level apps, use a secret manager:
- HashiCorp Vault
- AWS Secrets Manager
- Google Secret Manager
- Azure Key Vault
Example with AWS:
aws secretsmanager create-secret --name MyAppSecret --secret-string '{"API_KEY":"abcd12345"}'
Then fetch it securely in your Node.js app.
6. Rotate API Keys Regularly
- Generate new API keys every few months.
- Revoke old or unused keys immediately.
- Many providers (like Stripe, Twilio, AWS) allow rolling credentials.
7. Limit API Key Scope
- Use different API keys for dev, staging, and production.
- Apply the least privilege principle (only give access to what’s needed).
- Example: An API key for Google Maps should not also access Google Cloud Storage.
8. Validate API Key Access
If your app uses API keys for authentication, always validate them server-side:
const validApiKeys = [process.env.INTERNAL_API_KEY];
app.use('/api', (req, res, next) => {
const key = req.headers['x-api-key'];
if (!key || !validApiKeys.includes(key)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
});
9. Monitor and Alert
- Use logging tools (Winston, Bunyan) to detect unauthorized access.
- Set up alerts if an API key is used too frequently.
- Services like Datadog, New Relic, or ELK Stack help monitor API activity.
Conclusion
To secure environment variables and API keys in Node.js:
- Use
.env
files withdotenv
for local development - Never commit
.env
files to Git - Set secrets with environment variables in production
- Use secret managers (AWS, Vault, etc.) for sensitive apps
- Rotate and scope API keys regularly
- Validate and monitor API key usage
0 Comments