JAVASCRIPT
Securely Manage API Keys with Environment Variables in Node.js
Learn to safely store and access sensitive API keys and configuration in Node.js using environment variables and the `dotenv` package, preventing hardcoding secrets.
// Before running:
// 1. Install dotenv: npm install dotenv
// 2. Create a file named .env in the root of your project with content like:
// API_KEY_STRIPE="sk_test_********************"
// API_KEY_GOOGLE="AIza*******************"
// DATABASE_URL="mongodb://user:password@host:port/database"
// NODE_ENV=development
require('dotenv').config(); // Load environment variables from .env file
// Accessing API keys and other sensitive configurations
const stripeApiKey = process.env.API_KEY_STRIPE;
const googleApiKey = process.env.API_KEY_GOOGLE;
const databaseUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV || 'development'; // Provide a default
if (!stripeApiKey) {
console.error('ERROR: STRIPE API key not found. Please set API_KEY_STRIPE in your .env file or environment.');
// In a real application, you might exit or throw an error here.
}
console.log('--- Secure Configuration Loading ---');
console.log(`Node Environment: ${nodeEnv}`);
// Only log partial keys for safety, never the full key in production logs!
if (stripeApiKey) {
console.log(`Stripe API Key (partial): ${stripeApiKey.substring(0, 7)}...`);
}
if (googleApiKey) {
console.log(`Google API Key (partial): ${googleApiKey.substring(0, 7)}...`);
}
if (databaseUrl) {
// Be careful with database URLs, they often contain credentials.
// Consider parsing and logging only the host/database name.
console.log(`Database URL (host only, for example): ${new URL(databaseUrl).hostname}`);
}
// Example usage of a sensitive key (e.g., initializing a client)
// const stripe = require('stripe')(stripeApiKey);
// const googleMapsClient = require('@google/maps').createClient({ key: googleApiKey });
// Best practice: Ensure .env is in .gitignore to prevent committing sensitive data
// Example .gitignore entry:
/*
# .gitignore
.env
node_modules/
dist/
*/
How it works: This Node.js snippet demonstrates the secure practice of managing API keys and other sensitive configurations using environment variables via the `dotenv` package. Instead of hardcoding secrets directly into the codebase, they are loaded from a `.env` file (which should be excluded from version control using `.gitignore`) or directly from the system's environment. This prevents accidental exposure of credentials in repositories and allows for easy configuration changes across different deployment environments.