Introduction
Environment variables allow Node.js applications to store configuration values outside the main source code. They are commonly used for settings such as application mode, port numbers, database URLs, and API keys. In this chapter, you will practice reading environment variables, setting them from the terminal, using the process.env object, working with .env files, using the dotenv package, and keeping configuration separate from application code. Node.js Environment Variables practice questions with solutions help to understand the concepts.
Question 1: How do you read an environment variable using process.env?
Problem
Create an environment variable called USERNAME and read its value in a Node.js program.
Solution
Create index.js:
console.log("Username:", process.env.USERNAME);
On Windows Command Prompt, set the variable:
set USERNAME=Rishabh
Then run:
node index.js
Output
Username: Rishabh
On macOS/Linux, you can run:
USERNAME=Rishabh node index.js
Step-by-Step Explanation
processis a built-in Node.js object.process.envcontains environment variables available to the Node.js process.process.env.USERNAMEreads the value ofUSERNAME.- The value is displayed using
console.log().
Question 2: How do you use an environment variable for the server port?
Problem
Create a Node.js server that gets its port number from an environment variable.
Solution
Create index.js:
const http = require("http");
const PORT = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Server is running!");
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Set the port before starting the application.
On Windows Command Prompt:
set PORT=5000
node index.js
On macOS/Linux:
PORT=5000 node index.js
Output
Server running on port 5000
Step-by-Step Explanation
This line is important:
const PORT = process.env.PORT || 3000;
It means:
- Use
process.env.PORTif it exists. - Otherwise, use
3000.
So if PORT is:
5000
the application uses:
5000
If PORT is not set, it uses:
3000
Question 3: How do you create a .env file?
Problem
Create a .env file containing application configuration values.
Solution
Create a file named:
.env
Add:
PORT=4000
APP_NAME=My Node App
NODE_ENV=development
Your project can look like:
my-project/
├── .env
├── index.js
├── package.json
└── package-lock.json
Important Point
A .env file is simply a text file containing environment variables in the form:
KEY=value
For example:
PORT=4000
APP_NAME=My Node App
Step-by-Step Explanation
- Create a file named
.env. - Add configuration variables.
- Put one variable on each line.
- Load the variables into your Node.js application.
- Access them using
process.env.
A .env file is commonly kept out of version control when it contains secrets.
Question 4: How do you use the dotenv package?
Problem
Use the dotenv npm package to load variables from a .env file.
Solution
Install dotenv:
npm install dotenv
Create .env:
APP_NAME=My Node Application
PORT=5000
Create index.js:
require("dotenv").config();
console.log("Application:", process.env.APP_NAME);
console.log("Port:", process.env.PORT);
Run:
node index.js
Output
Application: My Node Application
Port: 5000
Step-by-Step Explanation
First:
require("dotenv").config();
loads variables from .env.
Then:
process.env.APP_NAME
reads the APP_NAME value.
And:
process.env.PORT
reads the PORT value.
Question 5: How do you use environment variables with an Express server?
Problem
Create an Express server that gets its port from an environment variable.
Solution
Install Express and dotenv:
npm install express dotenv
Create .env:
PORT=5000
Create index.js:
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Express server is running!");
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Run:
node index.js
Output
Server running on port 5000
Open:
http://localhost:5000
Browser Output
Express server is running!
Step-by-Step Explanation
dotenvloads.env.process.env.PORTreads the port.- Express creates the server.
- The application listens on the configured port.
- If
PORTis unavailable,3000is used.
Question 6: How do you create different environment variables for development and production?
Problem
Use NODE_ENV to identify whether your application is running in development or production mode.
Solution
Create .env:
NODE_ENV=development
Create index.js:
require("dotenv").config();
const environment = process.env.NODE_ENV;
if (environment === "development") {
console.log("Development mode is active.");
} else if (environment === "production") {
console.log("Production mode is active.");
} else {
console.log("Unknown environment.");
}
Run:
node index.js
Output
Development mode is active.
Step-by-Step Explanation
The code reads:
process.env.NODE_ENV
If the value is:
development
the development message is displayed.
If it is:
production
the production message is displayed.
Example
Change .env to:
NODE_ENV=production
Run again:
node index.js
Output:
Production mode is active.
Question 7: How do you use an API key through an environment variable?
Problem
Store an API key outside your JavaScript source code and read it using process.env.
Solution
Create .env:
API_KEY=my-secret-api-key
Create index.js:
require("dotenv").config();
const apiKey = process.env.API_KEY;
if (apiKey) {
console.log("API key is available.");
} else {
console.log("API key is missing.");
}
Run:
node index.js
Output
API key is available.
Step-by-Step Explanation
The .env file contains:
API_KEY=my-secret-api-key
The application reads it using:
process.env.API_KEY
The actual secret does not need to be written directly into your JavaScript code.
Question 8: What happens when an environment variable does not exist?
Problem
Check whether a required environment variable exists before starting your application.
Solution
Create index.js:
require("dotenv").config();
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
console.log("DATABASE_URL is missing.");
process.exit(1);
}
console.log("Database configuration found.");
Do not add DATABASE_URL to .env.
Run:
node index.js
Output
DATABASE_URL is missing.
The application then exits.
Step-by-Step Explanation
This code:
const databaseUrl = process.env.DATABASE_URL;
tries to read the variable.
If it does not exist, the value will be:
undefined
The condition:
if (!databaseUrl)
checks whether the value is missing.
Then:
process.exit(1);
stops the Node.js process with a non-zero exit status.
Question 9: How do you convert an environment variable from a string to a number?
Problem
Environment variables are read as strings. Convert a PORT value to a number before using it.
Solution
Create .env:
PORT=5000
Create index.js:
require("dotenv").config();
const PORT = Number(process.env.PORT);
console.log("Port:", PORT);
console.log("Type:", typeof PORT);
Run:
node index.js
Output
Port: 5000
Type: number
Step-by-Step Explanation
Environment variables are read as strings.
For example:
process.env.PORT
may give:
"5000"
Using:
Number(process.env.PORT)
converts it to:
5000
which is a JavaScript number.
Question 10: How do you build a complete Node.js application using environment variables?
Problem
Create a small Express application using:
.envdotenvPORTAPP_NAMENODE_ENV- npm scripts
- Express
Solution
Step 1: Create the project
mkdir env-practice
cd env-practice
Initialize npm:
npm init -y
Step 2: Install packages
npm install express dotenv
Step 3: Create .env
APP_NAME=Student API
PORT=5000
NODE_ENV=development
Step 4: Create index.js
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = Number(process.env.PORT) || 3000;
const APP_NAME = process.env.APP_NAME || "Node Application";
const NODE_ENV = process.env.NODE_ENV || "development";
app.get("/", (req, res) => {
res.json({
application: APP_NAME,
environment: NODE_ENV,
message: "Welcome to the Node.js application!"
});
});
app.listen(PORT, () => {
console.log(`${APP_NAME} is running.`);
console.log(`Environment: ${NODE_ENV}`);
console.log(`Server: http://localhost:${PORT}`);
});
Step 5: Add an npm script
Update package.json:
{
"scripts": {
"start": "node index.js"
}
}
Step 6: Start the application
npm start
Output
Student API is running.
Environment: development
Server: http://localhost:5000
Open:
http://localhost:5000
Browser Output
{
"application": "Student API",
"environment": "development",
"message": "Welcome to the Node.js application!"
}
Step-by-Step Explanation
- Create a Node.js project.
- Initialize npm.
- Install Express and dotenv.
- Create the
.envfile. - Store application configuration inside
.env. - Load
.envusingdotenv. - Read values using
process.env. - Convert
PORTinto a number. - Use the values in the Express application.
- Start the server using an npm script.
Key Takeaways
- Environment variables store configuration outside application code.
- Node.js provides access to environment variables through
process.env. - Environment variable values are read as strings.
process.env.PORTcan be used to configure a server port.- A fallback value can be provided using
||. .envfiles are commonly used to store local environment configuration.- The
dotenvpackage loads.envvalues intoprocess.env. NODE_ENVcan identify the current application environment.- API keys and database credentials should not be hard-coded into source code.
- Real secrets should not be committed to public Git repositories.
- Add
.envto.gitignorewhen it contains private configuration. .env.examplecan document the required variables without exposing real secrets.Number()orparseInt()can convert numeric environment variables into JavaScript numbers.- Missing required environment variables should be checked before starting an application.
- Environment variables make it easier to use different configuration for development, testing, and production.
- Environment variables are commonly used in Node.js APIs, Express applications, database connections, and deployment environments.
FAQs
1. What are environment variables in Node.js?
Environment variables are configuration values provided to an application from its environment rather than being hard-coded directly into the source code.
Examples include:
PORT
NODE_ENV
DATABASE_URL
API_KEY
Node.js makes them available through:
process.env
2. How do I access an environment variable in Node.js?
Use:
process.env.VARIABLE_NAME
For example:
console.log(process.env.PORT);
This reads the value of the PORT environment variable.
3. What is a .env file?
A .env file is a text file commonly used to store environment-specific configuration.
Example:
PORT=3000
NODE_ENV=development
APP_NAME=My Node App
Packages such as dotenv can load these values into process.env.
4. What is dotenv in Node.js?
dotenv is an npm package that loads variables from a .env file into process.env.
Install it with:
npm install dotenv
Then:
require("dotenv").config();
After that, you can access the variables:
console.log(process.env.PORT);
5. Are environment variables always strings?
Yes, values accessed through process.env are represented as strings.
For example:
PORT=5000
is read as:
process.env.PORT
which gives the string "5000".
If you need a number, convert it:
const PORT = Number(process.env.PORT);
6. Should I upload my .env file to GitHub?
Usually, no, especially if it contains secrets such as API keys, passwords, or database credentials.
Add it to .gitignore:
.env
You can create a safe .env.example file:
PORT=3000
API_KEY=your_api_key_here
This shows other developers which variables are required without exposing real secret values.
7. Why are environment variables useful in Node.js?
They allow the same application code to work with different configurations.
For example, development could use:
PORT=3000
NODE_ENV=development
while production could use different values.
This avoids changing your JavaScript source code every time the application’s environment changes.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
