JAVASCRIPT

Secure Environment Variable Management with Dotenv in Node.js

Safely manage sensitive configuration data like API keys and database credentials using environment variables with the dotenv library in Node.js.

// .env file content (create a file named .env in your project root):
// DB_HOST=localhost
// DB_USER=myuser
// DB_PASS=mysecurepassword
// API_KEY=supersecretapikey123
// NODE_ENV=development

// index.js (or main application file):
require('dotenv').config(); // Load environment variables from .env file

const express = require('express');
const app = express();

const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASS;
const apiKey = process.env.API_KEY;
const nodeEnv = process.env.NODE_ENV || 'development';

if (!dbHost || !dbUser || !dbPass || !apiKey) {
  console.error('CRITICAL: Missing essential environment variables!');
  process.exit(1);
}

app.get('/config', (req, res) => {
  res.json({
    dbHost: dbHost,
    dbUser: dbUser,
    // NEVER expose sensitive passwords or keys directly in API responses
    // dbPass: dbPass, 
    // apiKey: apiKey,
    environment: nodeEnv,
    message: 'Configuration loaded securely.'
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT} in ${nodeEnv} mode.`);
  console.log('Database Host:', dbHost);
  // console.log('Database User:', dbUser); // For demo, usually not logged in production
  // console.log('API Key:', apiKey); // For demo, usually not logged in production
});
How it works: This snippet illustrates how to manage sensitive application configurations (like database credentials or API keys) securely using environment variables with the `dotenv` library in Node.js. Instead of hardcoding secrets directly in your codebase, which could lead to accidental exposure in version control, `dotenv` loads variables from a `.env` file into `process.env`. This allows different configurations per environment (development, staging, production) and keeps secrets out of your repository. It's crucial to add `.env` to your `.gitignore` file. The code also includes a check for missing critical variables and emphasizes never exposing sensitive details like passwords directly in API responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs