
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.
- macOS or Linux:
PORT=4000 node app.js - Windows Command Prompt:
set PORT=4000&& node app.js - PowerShell:
$env:PORT=4000; node app.js
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.
- Set sensible defaults only for non-sensitive settings where a default is safe.
- Fail early when a required value is missing or invalid.
- Never assume environment-variable values are numbers or booleans; parse them explicitly.
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:
- Add
.envto.gitignoreand verify it isn’t already tracked in Git. - Commit a
.env.examplecontaining variable names and safe placeholder values, never real secrets. - Don’t print passwords, tokens, or full connection strings in logs or error messages.
- Limit who can view or change production variables, and rotate credentials if they’re exposed.
- Remember that anyone able to inspect a running process or deployment configuration may be able to access its environment.
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
- Loading too late: A module that reads
process.envbefore dotenv loads may capture an undefined value. Load configuration first. - Assuming values have types: Convert strings and validate the result before using it.
- Changing a file without restarting: Most Node.js apps read configuration at startup. Restart the process after changing environment settings unless your application explicitly supports reloading.
- Depending on a local file in production: Deployment environments may not include your
.envfile. Configure production variables through the platform instead. - Mixing up variable scopes: A variable set in one terminal, container, or service may not be available to another process.
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.