JAVASCRIPT
Securely Load Environment Variables
Safely manage sensitive configuration data and API keys by loading environment variables from a .env file, keeping them out of source control and enhancing security.
const path = require('path');
// Load environment variables from .env file
// Ensure .env is in your .gitignore!
require('dotenv').config({ path: path.resolve(__dirname, '.env') });
const DB_HOST = process.env.DB_HOST;
const DB_USER = process.env.DB_USER;
const DB_PASSWORD = process.env.DB_PASSWORD;
const API_KEY = process.env.API_KEY;
const NODE_ENV = process.env.NODE_ENV || 'development';
console.log('Node Environment:', NODE_ENV);
console.log('Database Host:', DB_HOST);
console.log('Database User:', DB_USER);
// IMPORTANT: Do NOT log sensitive information like passwords or API keys in production
// console.log('Database Password:', DB_PASSWORD);
// console.log('API Key:', API_KEY);
if (!DB_HOST || !DB_USER || !DB_PASSWORD || !API_KEY) {
console.error('ERROR: One or more critical environment variables are not set.');
process.exit(1); // Exit the process if critical variables are missing
}
// In a real application, you would use these variables
// to connect to databases, external services, etc.
// Example: const connection = new Database(DB_HOST, DB_USER, DB_PASSWORD);
console.log('All required environment variables loaded successfully.');
How it works: This snippet demonstrates how to securely load environment variables in a Node.js application using the `dotenv` package. Storing sensitive configuration (like database credentials, API keys) directly in code is a major security risk. `dotenv` allows you to define these variables in a `.env` file (which should always be excluded from version control using `.gitignore`), and then injects them into `process.env`. This practice keeps your secrets out of your repository, making your application more secure and easier to manage across different environments (development, staging, production) without code changes.