JAVASCRIPT
Secure API Key Management with Node.js Environment Variables
Learn to securely manage and access sensitive API keys in Node.js applications using environment variables, preventing their exposure in source code.
// .env file example (in project root, NOT committed to Git)
// API_KEY_SERVICE_A=your_secret_key_for_service_a
// API_KEY_SERVICE_B=your_other_secret_key
// app.js or config.js
require('dotenv').config(); // Make sure to install dotenv: npm install dotenv
const getServiceAApiKey = () => {
const apiKey = process.env.API_KEY_SERVICE_A;
if (!apiKey) {
console.error('API_KEY_SERVICE_A is not set in environment variables.');
// Depending on your application, you might throw an error, exit, or use a fallback
throw new Error('Missing API Key for Service A');
}
return apiKey;
};
const getServiceBApiKey = () => {
const apiKey = process.env.API_KEY_SERVICE_B;
if (!apiKey) {
console.error('API_KEY_SERVICE_B is not set in environment variables.');
throw new Error('Missing API Key for Service B');
}
return apiKey;
};
// Example usage
try {
const serviceAKey = getServiceAApiKey();
console.log('Using Service A Key (first few chars):', serviceAKey.substring(0, 5) + '...');
// In a real application, you would pass this key to your API client
// const serviceAClient = new ServiceAClient(serviceAKey);
const serviceBKey = getServiceBApiKey();
console.log('Using Service B Key (first few chars):', serviceBKey.substring(0, 5) + '...');
} catch (error) {
console.error('Application failed to start due to missing API keys:', error.message);
// process.exit(1); // Exit if critical keys are missing
}
// In production, environment variables are typically set directly on the server
// e.g., in Heroku config vars, AWS Lambda environment variables, Docker secrets, etc.
// The .env file is primarily for local development.
How it works: This snippet demonstrates how to securely manage API keys using environment variables in a Node.js application, typically facilitated by the `dotenv` package for local development. Instead of hardcoding keys directly into the source code, which is a security risk, they are loaded from the environment (or a `.env` file). This ensures sensitive credentials are not committed to version control and can be easily managed and rotated across different deployment environments (development, staging, production) without code changes.