Lesson 46 of 50 – Environment Variables
92% Completed
92%

Environment Variables in Node.js

Learn how to store configuration values, database credentials, API keys, and other application settings using environment variables.

Learning Goal: After this lesson, you will be able to create a .env file, load variables into Node.js, access them through process.env, and protect sensitive configuration values.

1. What Are Environment Variables?

Environment variables are named values available to a running application. They help us configure an application without writing environment-specific settings directly into the source code.

For example, an application may need these values:

PORT=3000
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=my_database_password
JWT_SECRET=your_secret_value
These values are examples only. Never publish real passwords, database credentials, or authentication secrets.

2. Why Do We Need Environment Variables?

Without Environment Variables
const PORT = 3000;
const DB_PASSWORD = "mySecretPassword";

Sensitive values are written directly in the code, which makes accidental exposure more likely.

With Environment Variables
const PORT = process.env.PORT;
const DB_PASSWORD = process.env.DB_PASSWORD;

The application reads configuration from its environment instead of hardcoding these values.

3. What Is process.env?

Node.js provides the process.env object to access environment variables available to the running process.

Example
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);

If the variables are set, you might see:

3000
development
If a variable is not set, its value is usually undefined. Environment variable values are strings, so convert them when you need numbers or booleans.

4. Create a Node.js Project

Open your terminal and create a project folder.

mkdir node-env-demo
cd node-env-demo
npm init -y

Your project will contain these files:

node-env-demo/
│
├── package.json
├── .env
├── .gitignore
└── app.js

5. Create a .env File

A .env file stores configuration values as NAME=value pairs. Create a file named .env in your project folder.

PORT=3000
APP_NAME=Soopro Pathshala
NODE_ENV=development
Do not add JavaScript syntax such as const PORT = 3000; inside a .env file. Use plain name-value pairs.

6. Install dotenv

The dotenv package loads variables from your .env file into process.env.

npm install dotenv

7. Read Environment Variables in Node.js

Create a file named app.js.

app.js
require('dotenv').config();

const appName = process.env.APP_NAME;
const port = process.env.PORT;
const environment = process.env.NODE_ENV;

console.log('Application:', appName);
console.log('Port:', port);
console.log('Environment:', environment);

Run the Program

node app.js

Output

Application: Soopro Pathshala
Port: 3000
Environment: development

The dotenv.config() call loads the file before the application reads its variables.

8. Use Environment Variables in an Express Server

Environment variables are often used to configure the port of an Express server.

Install Express

npm install express

Create server.js

require('dotenv').config();

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

const PORT = Number(process.env.PORT) || 3000;

app.get('/', (req, res) => {
    res.send('Welcome to Soopro Pathshala Node.js Tutorial!');
});

app.get('/about', (req, res) => {
    res.json({
        application: process.env.APP_NAME || 'Node.js Application',
        environment: process.env.NODE_ENV || 'development'
    });
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Run the Server

node server.js

Open the following URLs in your browser:

  • http://localhost:3000/
  • http://localhost:3000/about
Tip: You can change the port in your .env file without changing the JavaScript source code.

9. Protect Your .env File Using .gitignore

If you use Git, prevent your local .env file from being committed to the repository.

Create a file named .gitignore:

.env
node_modules/
Important: A .gitignore file does not remove secrets that have already been committed. If a secret is exposed, revoke or rotate it and remove it from the repository history as appropriate.

10. Store Database Credentials in Environment Variables

Database connection details should come from configuration rather than being written directly into your application code.

.env

DB_HOST=localhost
DB_USER=root
DB_PASSWORD=replace_with_your_database_password
DB_NAME=school_db

Read the Configuration

require('dotenv').config();

const dbConfig = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
};

console.log('Database host:', dbConfig.host);
console.log('Database name:', dbConfig.database);
This example only reads the configuration. It does not connect to a database. Avoid printing database passwords or other secrets to the console.

11. Environment Variables for JWT Secrets

In the previous lesson, you learned about JWT authentication. A JWT signing secret should be supplied through a secure environment configuration instead of being hardcoded.

.env

JWT_SECRET=replace_with_a_long_random_secret

Node.js Example

require('dotenv').config();

const jwtSecret = process.env.JWT_SECRET;

if (!jwtSecret) {
    throw new Error('JWT_SECRET is not configured');
}

// Use jwtSecret with your JWT library.
// Never print the secret or send it to the client.
For production, generate a strong random secret and configure it through your hosting provider's secret-management facility. Do not use the example value as a real secret.

12. Use Default Values

Sometimes an environment variable may not be configured. You can supply a default for non-sensitive settings.

const PORT = Number(process.env.PORT) || 3000;

const APP_NAME =
    process.env.APP_NAME || 'My Node.js Application';

console.log(APP_NAME);
console.log(PORT);

For example, if PORT is not set, the program uses port 3000.

Defaults are useful for settings such as a development port or application label. Do not silently substitute insecure defaults for required production secrets or credentials.

13. Environment Variables Are Strings

Values read from process.env are strings. Convert them before using them as numbers or booleans.

const port = Number(process.env.PORT || 3000);

const maintenanceMode =
    process.env.MAINTENANCE_MODE === 'true';

console.log(typeof port);       // number
console.log(maintenanceMode);   // true or false
Avoid using Boolean(process.env.MAINTENANCE_MODE) to parse the text "false". Any non-empty string, including "false", converts to true. Compare the string explicitly instead.

14. Set Environment Variables Without a .env File

Environment variables can also be supplied by the terminal or hosting platform.

Windows Command Prompt

set PORT=4000
node server.js

PowerShell

$env:PORT="4000"
node server.js

Linux or macOS

PORT=4000 node server.js

These examples set the variable for the process launched from that terminal. The exact scope and syntax depend on the operating system and shell.

15. Common Mistakes

Avoid These Mistakes
  • Forgetting to load dotenv before reading the .env values.
  • Using the wrong variable name, such as PORT and APP_PORT interchangeably.
  • Assuming all environment variable values are numbers or booleans.
  • Committing .env files containing secrets to Git.
  • Printing database passwords or JWT secrets in logs.
  • Using weak or predictable production secrets.
  • Assuming .gitignore protects secrets that were already committed.
  • Using development credentials in production.

16. Practical Assignment

Assignment: Configuration-Based Express Server

Complete these tasks:

  1. Create a new Node.js project.
  2. Install Express and dotenv.
  3. Create a .env file with PORT, APP_NAME, and NODE_ENV.
  4. Read the values using process.env.
  5. Create an Express server using the configured port.
  6. Create a route that displays the application name.
  7. Add .env and node_modules/ to .gitignore.
  8. Explain why passwords and JWT secrets should not be hardcoded.

17. Summary

  • Environment variables store application configuration.
  • process.env accesses variables in Node.js.
  • The dotenv package loads values from a .env file.
  • Use environment variables for ports and database configuration.
  • Protect secrets and keep local .env files out of Git.
  • Use secure hosting configuration for production secrets.
  • Validate and convert environment variable values when needed.

Test Your Knowledge – Environment Variables

Select the correct answer for each question.

1. Which object is used to access environment variables in Node.js?

2. Which package can load variables from a .env file?

3. How should you protect a .env file containing secrets?