← Back to all snippets
JAVASCRIPT

Securely Manage Configuration and Secrets with Environment Variables in Node.js

Learn to safely manage sensitive configuration and API keys using environment variables with Node.js and the `dotenv` library, avoiding hardcoding secrets.

// 1. Create a .env file in your project root (add to .gitignore!)
// .env content:
// DB_HOST=localhost
// DB_USER=myuser
// DB_PASS=supersecretpassword
// API_KEY=your_external_api_key_12345
// NODE_ENV=development

// 2. Install dotenv: npm install dotenv

// 3. In your main application file (e.g., app.js or index.js)
require('dotenv').config();

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

// Access environment variables
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASS; // AVOID logging or exposing sensitive data!
const apiKey = process.env.API_KEY;
const nodeEnv = process.env.NODE_ENV;

console.log(`Environment: ${nodeEnv}`);
console.log(`DB Host: ${dbHost}`);
console.log(`DB User: ${dbUser}`);
// console.log(`DB Pass: ${dbPass}`); // DO NOT LOG SENSITIVE INFO IN PRODUCTION
console.log(`API Key (partial): ${apiKey ? apiKey.substring(0, 5) + '...' : 'N/A'}`);

app.get('/', (req, res) => {
  res.send(`Hello from ${nodeEnv} environment!`);
});

// In a real app, you'd use these variables to configure your database connection,
// external API calls, etc.

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates the secure practice of managing application configuration and secrets using environment variables with the `dotenv` library. Instead of hardcoding sensitive data like database credentials or API keys directly in your code, they are stored in a `.env` file (which should always be added to `.gitignore`). `dotenv` loads these variables into `process.env`, allowing your application to access them without embedding them in the codebase. This method enhances security by isolating secrets from the source code, making them easier to manage, rotate, and preventing accidental exposure in version control.

Need help integrating this into your project?

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

Hire DigitalCodeLabs