Configure Node.js environment variables

3 min read07 November 2026

An application needs values that change between environments: port, database URL, API token, signing key. Writing them in code forces a code change for every deployment and exposes secrets in Git. Environment variables separate configuration from the program: the platform injects them at startup and your code reads them.

Read a variable

process.env holds variables provided by the environment and the platform. Note that everything is a string, even a number.

JavaScript
const port = Number(process.env.PORT);
if (!Number.isInteger(port) || port <= 0) {
  console.error("PORT missing or invalid");
  process.exit(1);
}

Validate at startup rather than at first use. An application that stops immediately with a clear message is easier to diagnose than a 500 error three hours later.

JavaScript
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
  console.error("DATABASE_URL missing");
  process.exit(1);
}

Only use default values for non-sensitive settings, such as a local development port. Never for a password, token or production URL.

Define variables in the panel

In the application hosting service, open the settings then the environment variables section. Add one name/value pair per line:

Text
DATABASE_URL = mysql://user:[email protected]:3306/app
API_TOKEN = replace-with-a-token
NODE_ENV = production

Two things to know: the process does not reload variables live, so restart the service after a change; and anyone with panel access can see the values. Do not share the account and do not leave a long-lived secret in a field you forget to clear.

Locally with a .env file

In development, a .env file at the project root avoids redefining variables for every command. Node.js 20.6 and later can read it directly:

Bash
node --env-file=.env index.js

The file looks like this:

Text
PORT=3000
NODE_ENV=development
DATABASE_URL=mysql://user:[email protected]:3306/app

On Node.js 18, which does not know that option, load a module such as dotenv at the top of the main file instead.

Add .env to .gitignore and commit a .env.example that contains only names and fake values. It is the simplest way to keep a secret out of Git history, where it remains even after the file is deleted.

Good practice

  • Never log process.env as a whole: the output often ends up in platform logs.
  • An exposed secret must be replaced, not just removed from code.
  • Keep development and production values separate; do not reuse the same token.
  • Validate the type and presence of every critical variable at startup.
  • Use explicit names: DATABASE_URL, API_TOKEN, SESSION_SECRET.
  • Do not wrap values in quotes in the panel, they become part of the value.

A well-named and validated variable beats a commented configuration file nobody reads.

Advertisement

Was this article helpful?

Read next