Introduction
When developing a Node.js application, you often need to configure values such as the server port, database connection details, API keys, and application environment. Keeping these values directly inside your source code can make an application harder to maintain and less secure.
Environment variables in Node.js provide a way to store configuration values outside your application code. You can use them to configure an application differently for development, testing, and production without changing the source code.
Node.js provides the process.env object to access environment variables. You can also use a .env file with Node.js’s built-in environment-variable support or a package such as dotenv.
In this tutorial, you will learn how environment variables work in Node.js, how to create and access them, how to use .env files, and how to manage configuration securely.
What Are Environment Variables in Node.js?
Environment variables are named values made available to a running process by its operating system, shell, container, hosting platform, or application configuration.
In Node.js, these values are accessible through the process.env object.
For example, an application might use these environment variables:
PORT=3000
NODE_ENV=development
DATABASE_HOST=localhost
Instead of hard-coding the port or environment name, the application can read them from process.env.
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);
Environment variables help separate application configuration from application logic. They are especially useful when the same application needs to run in multiple environments.
Important: Environment variables are not automatically encrypted. Avoid exposing their values in logs, error messages, public repositories, or client-side code.
Why Are Environment Variables Used?
Environment variables are useful for several reasons.
1. Manage Application Configuration
You can configure a server port, application mode, file paths, and other settings without editing the application code.
2. Keep Secrets Out of Source Code
Database passwords, API keys, and signing secrets can be supplied through the runtime environment rather than being written directly into source files.
These values still need to be protected through appropriate access controls and secret-management practices.
3. Support Multiple Environments
Development, testing, and production environments often require different settings.
For example:
| Environment Variable | Development Example | Production Example |
|---|---|---|
NODE_ENV |
development |
production |
PORT |
3000 |
Provided by the hosting platform |
DATABASE_HOST |
localhost |
A production database host |
LOG_LEVEL |
debug |
info |
These are illustrative values. Your actual configuration depends on the hosting platform and application requirements.
4. Simplify Deployment
You can deploy the same application code to different servers while providing different configuration values through environment variables.
What Is process.env in Node.js?
process.env is an object provided by Node.js that contains environment variables available to the running process.
You can read a variable using its name as a property.
console.log(process.env.NODE_ENV);
If NODE_ENV is set to development, the output will be :
development
If the variable is not defined, its value is usually undefined.
Example: Read Environment Variables
Create a file named app.js:
const port = process.env.PORT || 3000;
const environment = process.env.NODE_ENV || 'development';
console.log('Port:', port);
console.log('Environment:', environment);
Run the file:
node app.js
If the variables are not set, the output will be:
Port: 3000
Environment: development
The application uses default values when the corresponding environment variables are missing.
How to Set Environment Variables in Node.js
You can set environment variables through the command line, your operating system, a hosting platform, or a configuration file.
1. Set Environment Variables on Linux or macOS
Use the export command:
export PORT=4000
export NODE_ENV=development
node app.js
These variables are available to the process launched from that shell.
2. Set Environment Variables on Windows
In Windows Command Prompt, use:
set PORT=4000
set NODE_ENV=development
node app.js
In PowerShell, use:
$env:PORT = "4000"
$env:NODE_ENV = "development"
node app.js
These commands set variables for the current shell session and processes started from it. The exact behavior differs from permanently configuring system-level environment variables.
3. Use a Default Value
You can provide a fallback when a variable is missing.
const port = process.env.PORT || 3000;
console.log(`Server port: ${port}`);
If PORT is defined, the application uses that value. Otherwise, it uses 3000.
For configuration values that must be supplied, such as a production database password, it is often safer to stop the application with a clear error rather than silently use a fallback.
Using a .env File in Node.js
A .env file is a text file that contains environment-variable assignments. It is a convenient way to manage local development configuration.
For example, create a file named .env in your project root:
PORT=3000
NODE_ENV=development
APP_NAME=TechFliez
Each line defines a variable using the format NAME=value.
You can then load these values into your Node.js application.
Method 1: Use Node.js Built-In Environment File Support
Modern Node.js versions support loading environment variables from a .env file with the –env-file command-line option.
Run your application like this:
node --env-file=.env app.js
Then access the variables through process.env:
console.log(process.env.PORT);
console.log(process.env.APP_NAME);
If your Node.js version supports this option, you do not need to install an additional package just to load a basic .env file.
For supported Node.js versions, you can check the available command-line options with:
node --help
Method 2: Use the dotenv Package
The dotenv package is another widely used way to load .env files.
Install it:
npm install dotenv
Load the file at the beginning of your application:
require('dotenv').config();
const port = process.env.PORT || 3000;
const appName = process.env.APP_NAME || 'My Application';
console.log('Port:', port);
console.log('Application:', appName);
Calling require(‘dotenv’).config() loads values from the default .env file into process.env.
Important: Choose either Node.js’s built-in –env-file option or dotenv for a simple setup. You generally do not need both unless your configuration specifically requires them.
Create a Node.js Server Using Environment Variables
Let’s create a simple Express.js application that uses environment variables to configure the server port and application name.
Step 1: Install Express
Create a project and install Express:
mkdir nodejs-env-example
cd nodejs-env-example
npm init -y
npm install express dotenv
Step 2: Create the .env File
Add the following configuration to .env:
PORT=3000
APP_NAME=TechFliez
Step 3: Create app.js
require('dotenv').config();
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const appName = process.env.APP_NAME || 'My Application';
app.get('/', (req, res) => {
res.json({
message: `Welcome to ${appName}`,
port: Number(port)
});
});
app.listen(port, () => {
console.log(`${appName} is running on port ${port}`);
});
Step 4: Run the Application
Execute:
node app.js
You should see a message similar to:
TechFliez is running on port 3000
Open the following URL in your browser:
http://localhost:3000
The response will look like this:
{
"message": "Welcome to TechFliez",
"port": 3000
}
Now you can change the application name or port in the .env file without changing the route code.
Restart the application after changing the file so the new configuration is loaded.
Environment Variables Are Strings
One important detail is that values in process.env are generally represented as strings.
For example:
PORT=3000
DEBUG=true
You can read these values as follows:
console.log(typeof process.env.PORT);
console.log(typeof process.env.DEBUG);
The output is:
If you need a number, convert it explicitly:
const port = Number(process.env.PORT);
If you need a boolean, compare the value explicitly:
const debug = process.env.DEBUG === 'true';
Avoid using Boolean(process.env.DEBUG) to parse text such as “false”, because every non-empty string is truthy in JavaScript.
For required configuration, validate that the converted values are valid before starting the application.
Using Environment Variables for Database Configuration
Environment variables are commonly used to configure database connections.
For example, a database configuration file might read:
const databaseConfig = {
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME
};
module.exports = databaseConfig;
The corresponding local .env file might contain:
DATABASE_HOST=localhost
DATABASE_USER=app_user
DATABASE_PASSWORD=replace_with_a_local_password
DATABASE_NAME=my_application
This example demonstrates how configuration values can be separated from application code. It does not connect to a database by itself.
For production, use your hosting provider’s environment configuration or a secrets manager where possible. Restrict access to credentials, rotate them when needed, and avoid committing real passwords to source control.
Validate Required Environment Variables
A common mistake is allowing an application to start when essential configuration is missing.
For example, an application that requires a JWT signing secret should not silently continue with an empty value or a public default secret.
You can validate required values when the application starts:
const requiredVariables = [
'DATABASE_HOST',
'DATABASE_USER',
'DATABASE_PASSWORD'
];
const missingVariables = requiredVariables.filter(
(name) => !process.env[name]
);
if (missingVariables.length > 0) {
throw new Error(
`Missing required environment variables: ${missingVariables.join(', ')}`
);
}
This code checks whether the required variables exist and are non-empty. For more complex configuration, you may also want to validate types, allowed values, numeric ranges, and URL formats.
Never include the actual secret values in validation errors or logs.
Best Practices for Node.js Environment Variables
Follow these practices when working with environment variables in real projects.
1. Do Not Commit .env Files
Add .env to your .gitignore file:
.env
.env.*
!.env.example
This pattern excludes .env files while allowing a sample file named .env.example. Adjust it if your project intentionally uses other environment files.
2. Provide a .env.example File
Create a sample configuration file containing the variable names but no real credentials.
PORT=3000
NODE_ENV=development
DATABASE_HOST=localhost
DATABASE_USER=
DATABASE_PASSWORD=
This helps other developers understand which variables they need to configure.
3. Never Expose Secrets to Frontend Code
Server-side environment variables should remain on the server. Do not embed private keys, database passwords, or server secrets in frontend JavaScript bundles or public API responses.
4. Use Different Configuration for Different Environments
Development and production often require different database connections, logging settings, and security options. Configure these values through the relevant environment rather than changing source code manually.
5. Validate Configuration at Startup
Check required variables and ensure their values are valid before starting the server. Clear validation errors make deployment problems easier to diagnose.
6. Use a Secrets Manager for Sensitive Values
For production applications, use your hosting platform’s secret configuration or a dedicated secrets manager when available. Restrict access and rotate sensitive credentials when appropriate.
7. Avoid Logging Sensitive Values
Do not print the complete process.env object or log passwords, access tokens, API keys, or signing secrets.
Common Mistakes When Using Environment Variables
Here are some common mistakes to avoid:
- Forgetting to load the .env file: With dotenv, call require(‘dotenv’).config() before reading the variables.
- Using the wrong variable name: Environment-variable names must match exactly, including capitalization on case-sensitive systems.
- Assuming values have numeric or boolean types: Convert and validate values explicitly.
- Committing real secrets to Git: Keep private configuration out of source control.
- Changing .env without restarting the app: Most applications load configuration when they start, so restart the process to apply changes.
- Using insecure default secrets: Never use a predictable fallback for production signing keys or passwords.
- Exposing server secrets to the browser: Keep private configuration in server-side code.
- Ignoring missing variables: Validate required settings before the application begins serving requests.
Conclusion
Environment variables in Node.js help you manage application configuration without hard-coding settings into your source code. Using process.env, you can read values such as the server port, application environment, database configuration, and API credentials.
For local development, you can load variables using Node.js’s built-in –env-file option or the dotenv package. In production, configure values through your hosting environment or a secrets manager.
By validating configuration, protecting secrets, and keeping environment-specific settings separate from application logic, you can build Node.js applications that are easier to maintain, deploy, and secure.