Environment Variables

Hardcoding sensitive information like API keys, database credentials, or secret keys in your code is a major security risk. Instead, you should use Environment Variables.

1. Using .env files

The dotenv package is the standard tool for loading environment variables from a .env file into process.env.

npm install dotenv

Create a .env file:

PORT=5000
MONGO_URI=mongodb://localhost/mydb
JWT_SECRET=mySuperSecretKey123

2. Accessing in Code

Require dotenv as early as possible in your application (usually the very first line of app.js).

require('dotenv').config();

const port = process.env.PORT || 3000;
console.log(`Running on port ${port}`);

const db = process.env.MONGO_URI;

3. Security Hierarchy

In production environments (like AWS, Heroku, or Vercel), you don't use .env files. Instead, you set variables directly in the platform's dashboard. Node.js treats these as higher priority than local files.

CRITICAL: Always add .env to your .gitignore file to ensure your secrets are never pushed to GitHub.

4. Best Practices

  • Use process.env.NODE_ENV to check if the app is in 'development' or 'production'.
  • Group configurations into a config.js file that exports values from process.env.