FROMDEV

How to Configure Environment Variables for Node.js Applications

How to Configure Environment Variables for Node.js Applications

Set Up Node.js Configuration That Works in Every Environment

Moving a Node.js application from a laptop to a test server or production can expose a common problem: the app still expects local settings, or sensitive credentials have been bundled with its code. Node.js environment variables solve this by letting you supply configuration from outside the application. Define them in your shell, a local .env file, or your hosting platform, then read them with process.env. Here’s how to set them up safely, validate them, and avoid common deployment mistakes.

What Node.js Environment Variables Do

Environment variables are named values provided to a running process. They’re useful for settings that vary by environment, such as a port, database URL, log level, or API credential. Your application reads these values at runtime instead of hard-coding them into source files.

Node.js exposes environment variables through the global process.env object. Its values are strings, so numbers and booleans need explicit conversion. For example, process.env.PORT may contain "3000", not the number 3000.

Set Variables in Your Shell

For a quick local test, set a variable in the same terminal session where you start the application. The syntax differs across operating systems and shells.

These values apply to the process launched from that shell. They usually disappear when you close the session, which makes this approach handy for testing but less convenient for a project with several settings.

Use dotenv for Local Development

The dotenv package loads values from a .env file into process.env. It’s a straightforward option for local development when your Node.js version or application setup doesn’t use Node’s built-in environment-file support.

1. Install the package

npm install dotenv

2. Create a local .env file

PORT=4000
DATABASE_URL=postgres://user:password@localhost:5432/app
LOG_LEVEL=debug

Keep each assignment on its own line. Don’t add JavaScript syntax such as const or a trailing semicolon. Quote values when needed, especially if they contain spaces or characters that could be interpreted by the parser.

3. Load the file before reading configuration

For a CommonJS application, load dotenv near the start of the entry point:

require('dotenv').config();

const port = Number(process.env.PORT || 3000);
console.log(`Server port: ${port}`);

For an ES module application, import dotenv before the code that uses the variables:

import 'dotenv/config';

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

Alternatively, supported modern Node.js versions can load an environment file with the command-line option --env-file, for example node --env-file=.env app.js. Check the documentation for the Node.js version you deploy before relying on this option. Avoid loading the same settings through multiple mechanisms unless you understand which value takes precedence.

Read and Validate Configuration

Reading values directly throughout an application can hide missing settings and lead to confusing runtime errors. A small configuration module gives you one place to convert and validate them.

const port = Number(process.env.PORT ?? 3000);
const databaseUrl = process.env.DATABASE_URL;

if (!Number.isInteger(port) || port < 1 || port > 65535) {
  throw new Error('PORT must be a valid TCP port');
}

if (!databaseUrl) {
  throw new Error('DATABASE_URL is required');
}

module.exports = { port, databaseUrl };

Import this module where configuration is needed. For larger applications, a validation library can help define required values, allowed formats, and useful startup errors.

Configure Production Secrets Safely

A local .env file is convenient, but it should not be your production secrets store. In production, configure values through your hosting provider, container platform, orchestrator, or a dedicated secrets manager. The application can still read them using process.env; the platform handles how they’re supplied.

To reduce the chance of exposing credentials:

Environment variables keep secrets out of source code, but they are not automatically encrypted or protected from every user with access to the runtime. Follow your platform’s access controls and secret-management guidance.

Common Pitfalls to Avoid

When setting up your development environment, you may also find FromDev’s guide to choosing the Node.js version in VS Code helpful. If you’re comparing editors, see 15+ Node.js IDEs.

Conclusion

Node.js environment variables let you change application settings without changing application code. Use shell variables for quick tests, dotenv or Node’s supported --env-file option for local development, and your hosting platform’s configuration or secrets manager in production. Read values through process.env, validate them at startup, and keep credentials out of version control and logs. That small amount of discipline makes configuration more portable, predictable, and safer to maintain.

Exit mobile version