JAVASCRIPT
Securely Load API Keys from Environment Variables (Node.js)
Learn to secure sensitive API keys in your Node.js applications by loading them from environment variables instead of hardcoding, using the 'dotenv' package.
// 1. Install dotenv: npm install dotenv
// 2. Create a .env file in your project root:
// API_KEY=your_super_secret_api_key_123
// DB_HOST=localhost
require('dotenv').config();
const MY_API_KEY = process.env.API_KEY;
const DATABASE_HOST = process.env.DB_HOST;
const NODE_ENV = process.env.NODE_ENV || 'development';
if (!MY_API_KEY) {
console.error('CRITICAL: API_KEY environment variable is not set!');
process.exit(1);
}
console.log(`API Key loaded (first 5 chars): ${MY_API_KEY.substring(0, 5)}...`);
console.log(`Database Host: ${DATABASE_HOST}`);
console.log(`Environment: ${NODE_ENV}`);
// Use MY_API_KEY in your API requests or configurations
// const headers = { 'Authorization': `Bearer ${MY_API_KEY}` };
How it works: This Node.js snippet demonstrates the secure practice of loading sensitive API keys and other configuration variables from environment files using the `dotenv` package. Instead of hardcoding keys directly in your code, which is a security risk, `dotenv` loads key-value pairs from a `.env` file into `process.env`. This keeps credentials out of your codebase, making them easier to manage across different environments (development, staging, production) and preventing accidental exposure in version control.