Environment Variables in Express

📘 Express.js 👁 63 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Environment variables are used to store configuration values like API keys, database credentials, and ports outside your code. This makes your app more secure and flexible across different environments (development, testing, production).


1. Why Use Environment Variables?

  • Keep sensitive data out of the source code

  • Easily switch configuration for different environments

  • Prevent accidental exposure of secrets in version control

Common examples:

PORT=3000 DB_HOST=localhost DB_USER=root DB_PASSWORD=password JWT_SECRET=mysecretkey

2. Using .env Files

  1. Install dotenv package:

npm install dotenv
  1. Create a .env file in the root of your project:

PORT=3000 DB_HOST=localhost DB_USER=root DB_PASSWORD=secret JWT_SECRET=mysecretkey
  1. Load environment variables in app.js:

require('dotenv').config(); const express = require('express'); const app = express(); const PORT = process.env.PORT || 5000; app.get('/', (req, res) => { res.send('Hello Express with Environment Variables!'); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
  • process.env.VARIABLE_NAME is used to access variables

  • || provides a default value if variable is missing


3. Using Environment Variables for Database Configuration

const mysql = require('mysql2'); const db = mysql.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME }); db.connect((err) => { if (err) throw err; console.log('Connected to MySQL database'); });
  • Keeps credentials secure and flexible


4. Using Environment Variables for JWT Secret

const jwt = require('jsonwebtoken'); const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
  • Avoid hardcoding secret keys

  • Easier to rotate keys in production


5. Best Practices

  1. Do not commit .env to Git – add it to .gitignore.

  2. Use different .env files for development, testing, and production.

  3. Keep sensitive credentials outside source code.

  4. Access variables via process.env.VARIABLE_NAME only.

  5. Consider dotenv-safe or dotenv-expand for more advanced validation.


6. Example Project Structure

express-app/ │ ├─ .env ├─ app.js └─ package.json
  • .env → Stores environment variables

  • app.js → Uses dotenv to load variables

  • Keeps configuration clean and secure


Environment variables are essential for real-world Express apps, especially when dealing with databases, authentication, and third-party services.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes