Learn how to store configuration values, database credentials, API keys, and other application settings using environment variables.
.env file, load variables into Node.js,
access them through process.env, and protect sensitive
configuration values.
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
const PORT = 3000;
const DB_PASSWORD = "mySecretPassword";
Sensitive values are written directly in the code, which makes accidental exposure more likely.
const PORT = process.env.PORT;
const DB_PASSWORD = process.env.DB_PASSWORD;
The application reads configuration from its environment instead of hardcoding these values.
Node.js provides the process.env object to access
environment variables available to the running process.
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);
If the variables are set, you might see:
3000
development
undefined. Environment variable values are
strings, so convert them when you need numbers or booleans.
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
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
const PORT = 3000;
inside a .env file. Use plain name-value pairs.
The dotenv package loads variables from your
.env file into process.env.
npm install dotenv
Create a file named 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);
node app.js
Application: Soopro Pathshala
Port: 3000
Environment: development
The dotenv.config() call loads the file before the
application reads its variables.
Environment variables are often used to configure the port of an Express server.
npm install express
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}`);
});
node server.js
Open the following URLs in your browser:
http://localhost:3000/http://localhost:3000/about.env file without changing the JavaScript source code.
If you use Git, prevent your local .env file from
being committed to the repository.
Create a file named .gitignore:
.env
node_modules/
Database connection details should come from configuration rather than being written directly into your application code.
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=replace_with_your_database_password
DB_NAME=school_db
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);
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.
JWT_SECRET=replace_with_a_long_random_secret
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.
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.
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
Boolean(process.env.MAINTENANCE_MODE) to
parse the text "false". Any non-empty string, including "false",
converts to true. Compare the string explicitly instead.
Environment variables can also be supplied by the terminal or hosting platform.
set PORT=4000
node server.js
$env:PORT="4000"
node server.js
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.
Complete these tasks:
process.env accesses variables in Node.js.dotenv package loads values from a .env file.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?