JAVASCRIPT

Securely Manage Environment Variables in Node.js Applications

Best practices for managing sensitive configuration like API keys and database credentials using environment variables in Node.js, preventing hardcoding.

require('dotenv').config(); // Load environment variables from .env file

// Accessing environment variables
const DB_HOST = process.env.DB_HOST || 'localhost';
const DB_USER = process.env.DB_USER || 'root';
const DB_PASSWORD = process.env.DB_PASSWORD; // No default for sensitive credentials
const API_KEY = process.env.API_KEY;
const NODE_ENV = process.env.NODE_ENV || 'development';

function connectToDatabase() {
    if (!DB_PASSWORD) {
        console.error('Error: DB_PASSWORD environment variable is not set.');
        // In a real application, you might throw an error or exit process
        return null;
    }
    console.log(`Connecting to database at ${DB_HOST} as ${DB_USER}...`);
    // Example database connection (pseudo-code)
    // return new DatabaseClient({
    //     host: DB_HOST,
    //     user: DB_USER,
    //     password: DB_PASSWORD
    // });
    console.log('Database connection details loaded securely.');
}

function makeApiRequest() {
    if (!API_KEY) {
        console.error('Error: API_KEY environment variable is not set.');
        return null;
    }
    console.log(`Making API request with key: ${API_KEY.substring(0, 5)}...`); // Log first 5 chars for debug
    // Example API call (pseudo-code)
    // return fetch(`https://api.example.com/data?key=${API_KEY}`);
    console.log('API request made with securely loaded key.');
}

console.log(`Application running in ${NODE_ENV} mode.`);

connectToDatabase();
makeApiRequest();

// Example of a .env file content:
// DB_HOST=your_db_host
// DB_USER=your_db_user
// DB_PASSWORD=your_db_secret_password
// API_KEY=your_api_secret_key_12345
// NODE_ENV=production
How it works: This Node.js snippet demonstrates the crucial security practice of managing sensitive configuration data using environment variables, facilitated by the popular `dotenv` package. Instead of hardcoding credentials like database passwords or API keys directly in the code, they are loaded from a `.env` file (which should be excluded from version control, e.g., via `.gitignore`) into `process.env`. This prevents sensitive information from being exposed in your source code repository and allows different configurations for development, staging, and production environments, significantly enhancing application security and deployment flexibility.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs