Paramclasses Academy - Blog

Tutorials Details

←
Post 15 of 40
→

Environment Variables in Node.js: Using .env Files Safely

Environment Variables in Node.js: Using .env Files Safely

October 29, 2026

✦ Environment Variables in Node.js: Using .env Files Safely

❖ Introduction

When developing a Node.js application, you may need to use sensitive or environment-specific information such as database credentials, API keys, email passwords, and server configuration settings.

Writing these values directly inside your source code is not a good practice. If the code is shared publicly or uploaded to a repository, sensitive information may be exposed.

Environment variables in Node.js provide a way to store configuration values separately from application code. They also make it easier to run the same application in development, testing, and production environments with different settings.

In this tutorial, we will learn what environment variables are, how to access them using process.env, how to use .env files, and how to protect sensitive configuration values in real-world projects.

✦ What Are Environment Variables in Node.js?

Environment variables are key-value pairs provided to a running process by its environment.

For example, a Node.js application might use these variables:

PORT=3000
NODE_ENV=development
DB_HOST=localhost
DB_USER=app_user

Your application can read these values without hardcoding them directly into JavaScript files.

Environment variables are commonly used for:

  • Server port configuration.

  • Database connection settings.

  • API keys and access tokens.

  • Email service configuration.

  • Application environment selection.

  • Third-party service credentials.

Remember that environment variables are not automatically encrypted. Anyone with sufficient access to the process or its environment may be able to read them, so access controls are still important.

❖ Why Should You Use Environment Variables?

1. Better Security

Keeping credentials out of source code reduces the risk of accidentally exposing them when sharing or publishing code.

2. Easy Configuration

You can change a server port or database host without editing your application logic.

3. Multiple Environments

Development, testing, and production can use different configuration values.

4. Easier Deployment

Hosting providers and deployment platforms commonly allow you to configure environment variables through their dashboards or deployment settings.

✦ Step 1: Create a Node.js Project

First, ensure Node.js and npm are installed on your computer.

Open the terminal and create a project folder:

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

Create a file named app.js.

✦ Step 2: Read Environment Variables Using process.env

Node.js exposes environment variables through the process.env object.

Add the following code to app.js:

console.log("Server Port:", process.env.PORT);
console.log("Environment:", process.env.NODE_ENV);

Now set environment variables in your terminal before running the application.

Windows Command Prompt:

set PORT=3000
set NODE_ENV=development
node app.js

Windows PowerShell:

$env:PORT="3000"
$env:NODE_ENV="development"
node app.js

macOS or Linux:

PORT=3000 NODE_ENV=development node app.js

Expected output:

Server Port: 3000
Environment: development

These commands set the variables for the launched process and, depending on the shell, its child processes. They do not necessarily save the values permanently in your operating system.

✦ Step 3: Use a .env File in Node.js

A .env file stores configuration values in a simple text format.

Create a file named .env in your project directory:

PORT=3000
NODE_ENV=development
APP_NAME=Param Classes

Recent versions of Node.js support loading environment variables from a file using the built-in --env-file option.

Run the application like this:

node --env-file=.env app.js

Update app.js:

console.log("Application:", process.env.APP_NAME);
console.log("Port:", process.env.PORT);
console.log("Environment:", process.env.NODE_ENV);

Expected output:

Application: Param Classes
Port: 3000
Environment: development

This method avoids installing an additional package when your Node.js version supports --env-file.

❖ Alternative: Use dotenv

The dotenv package is another widely used option, especially in existing projects or workflows that already use it.

Install the package:

npm install dotenv

At the beginning of app.js, add:

require("dotenv").config();

console.log("Application:", process.env.APP_NAME);
console.log("Port:", process.env.PORT);

Run:

node app.js

Use either Node.js's --env-file option or dotenv to load the file. For a simple project, you generally do not need both.

✦ Step 4: Use Environment Variables in an Express.js Server

Let's build a small Express.js application that reads its port from an environment variable.

Install Express:

npm install express

Create server.js:

const express = require("express");

const app = express();

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

app.get("/", (req, res) => {
    res.send("Welcome to Param Classes Node.js Tutorial!");
});

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

If you use the .env file from the previous example, start the server with:

node --env-file=.env server.js

Open http://localhost:3000 in your browser.

You should see:

Welcome to Param Classes Node.js Tutorial!

The port is now configurable without changing the server code.

For production applications, validate configuration values rather than assuming every environment variable is valid.

✦ Step 5: Use Environment Variables for Database Configuration

Database credentials should not be hardcoded into application files.

For example, your .env file might contain:

DB_HOST=localhost
DB_PORT=3306
DB_USER=app_user
DB_PASSWORD=replace_with_your_local_password
DB_NAME=student_management

The following example shows how you might read these values in JavaScript:

const dbConfig = {
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT || 3306),
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
};

console.log({
    host: dbConfig.host,
    port: dbConfig.port,
    database: dbConfig.database
});

This example intentionally avoids printing the database password.

To connect to MySQL, you would pass this configuration to a suitable MySQL driver, such as mysql2. Ensure the required variables exist before creating the connection, and never commit real credentials to your source repository.

✦ Step 6: Protect Your .env File with .gitignore

One of the most important security steps is preventing private environment files from being committed to Git.

Create a file named .gitignore in your project directory:

node_modules/
.env
.env.*
!.env.example

This excludes .env and similarly named environment files while allowing an example configuration file.

Create .env.example with placeholder values:

PORT=3000
NODE_ENV=development
DB_HOST=localhost
DB_PORT=3306
DB_USER=your_database_user
DB_PASSWORD=your_database_password
DB_NAME=your_database_name

The example file documents which variables are required without containing actual secrets.

Important: If a secret has already been committed or exposed, adding .env to .gitignore does not remove it from the repository's history. Rotate the affected credentials and follow the repository or provider's secret-removal procedure.

✦ Step 7: Validate Required Environment Variables

An application should fail early with a clear message when required configuration is missing.

Create config.js:

const requiredVariables = [
    "DB_HOST",
    "DB_USER",
    "DB_PASSWORD",
    "DB_NAME"
];

for (const variable of requiredVariables) {
    if (!process.env[variable]) {
        throw new Error(
            `Missing required environment variable: ${variable}`
        );
    }
}

module.exports = {
    dbHost: process.env.DB_HOST,
    dbUser: process.env.DB_USER,
    dbPassword: process.env.DB_PASSWORD,
    dbName: process.env.DB_NAME
};

Load your environment file before importing this configuration module:

node --env-file=.env app.js

If a required variable is missing, the application reports which configuration key needs to be supplied. Avoid including the actual secret value in the error message.

✦ Best Practices for Using Environment Variables

❖ Never commit real secrets. Keep .env files out of version control.

❖ Use secure deployment settings. Store production credentials in your hosting platform's secret or environment-variable management system.

❖ Validate configuration. Check required variables and their expected formats at startup.

❖ Do not print secrets in logs. Avoid logging passwords, tokens, API keys, or complete database connection strings.

❖ Use different credentials for each environment. Development credentials should not be reused for production.

❖ Rotate exposed credentials. If a secret is accidentally published, replace it immediately.

❖ Understand precedence. Values provided by the process environment may take precedence over values loaded from a file. Check the behavior of the specific loading method you use.

❖ Remember that .env is not encryption. The file is only a convenient way to supply configuration values. File permissions and deployment security still matter.

✦ Frequently Asked Questions (FAQs)

1. What is process.env in Node.js?

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

2. What is a .env file?

A .env file is a text file used to store configuration key-value pairs, such as a local server port or database settings.

3. Do I need dotenv in every Node.js project?

No. Recent Node.js versions support loading environment files using --env-file. The dotenv package remains useful in projects that prefer or require that approach.

4. Is a .env file secure?

Not by itself. It can help separate secrets from source code, but it must be protected from unauthorized access and excluded from version control.

5. Can environment variables store database passwords?

Yes, but access to those values must be restricted. For production systems, use your hosting platform's supported secret-management facilities where appropriate.

6. How do I change the Node.js server port?

Read the port from process.env.PORT and configure that variable in your shell, .env file, or deployment platform.

✦ Conclusion

Environment variables are an important part of building configurable and maintainable Node.js applications. By using process.env, loading .env files appropriately, validating required values, and protecting credentials with .gitignore and secure deployment settings, developers can avoid common configuration mistakes.

Practise these examples and then apply the same approach to your Express.js projects, MySQL connections, email services, and REST APIs.

Keep learning and keep building with Param Classes!

←
Post 15 of 40
→