← Back to all snippets
JAVASCRIPT

Securely Load Environment Variables in Node.js

Learn to safely manage sensitive data like API keys and database credentials in Node.js applications using environment variables, crucial for production security.

const path = require('path');

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
}

const config = {
  PORT: process.env.PORT || 3000,
  DB_HOST: process.env.DB_HOST,
  DB_USER: process.env.DB_USER,
  DB_PASSWORD: process.env.DB_PASSWORD,
  API_SECRET_KEY: process.env.API_SECRET_KEY,
  JWT_SECRET: process.env.JWT_SECRET,
  validateConfig: () => {
    const requiredVars = ['DB_HOST', 'DB_USER', 'DB_PASSWORD', 'API_SECRET_KEY', 'JWT_SECRET'];
    for (const varName of requiredVars) {
      if (!config[varName]) {
        console.error(`ERROR: Missing required environment variable: ${varName}`);
        process.exit(1);
      }
    }
  }
};

config.validateConfig();

module.exports = config;
How it works: This Node.js snippet demonstrates the secure handling of sensitive application configurations like API keys and database credentials using environment variables. It utilizes the `dotenv` package (for local development) to load variables from a `.env` file, ensuring these secrets are never hardcoded or committed to version control. In production, these variables are typically set directly by the hosting environment. The `validateConfig` function adds an important security layer by verifying that all critical environment variables are present at application startup, preventing potential runtime failures or security vulnerabilities from misconfigurations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs