October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Pass Environment Variables to Node.js Apps With PM2

Pass environment variables to Node.js under PM2 with inline shell assignments or an ecosystem file. This guide covers --update-env, env_* blocks, staging and production selection, secret injection, validation, and troubleshooting.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PM2 accepts environment variables in two documented ways: assign them inline when starting or restarting an app, or define them in an ecosystem configuration file. Your Node.js code reads either form through process.env. For a changed inline value to reach an existing PM2 process, restart or reload with --update-env. For an ecosystem file, restart or reload after editing the file; PM2 applies the updated values then.

  • One-off start: ENV_VAR=value pm2 start app.js
  • Repeatable configuration: an ecosystem file with env and optional env_production, env_staging, or other named blocks
  • Environment selection: pm2 start ecosystem.config.js --env production

How PM2 environment variables reach your Node.js app

When PM2 launches a Node.js process, it gives that process an environment inherited from the command that started it and from the PM2 configuration. Node exposes those values as strings on the global process.env object. A variable named API_URL is therefore read in application code as process.env.API_URL.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PM2’s two supported configuration patterns solve different operational problems. An inline assignment is convenient for a quick start or a temporary override. An ecosystem file makes the intended environment explicit, repeatable, and easier to use when several applications or deployment stages are involved.

Read the value in application code

const apiUrl = process.env.API_URL;

console.log('API URL:', apiUrl);

Environment values arrive as text. If your code needs a number or a boolean, convert and validate it deliberately instead of relying on JavaScript truthiness:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
const port = Number.parseInt(process.env.PORT ?? '', 10);
const debug = process.env.DEBUG === 'true';

if (!Number.isInteger(port)) {
  throw new Error('PORT must be an integer');
}

For required settings, fail during startup with a useful message. A process that starts with an undefined database URL can produce a much less actionable error later, after handling traffic.

function required(name) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

const databaseUrl = required('DATABASE_URL');

Method 1: pass a variable on the PM2 command line

Prefix the PM2 command with a shell assignment:

ENV_VAR=value pm2 start app.js

For example:

API_URL=https://api.example.com NODE_ENV=production pm2 start app.js --name my-node-app

PM2 starts the application with both values, and the code can access them as process.env.API_URL and process.env.NODE_ENV. This approach is useful when you are testing a value, performing a one-off launch, or wrapping PM2 in a deployment script that already exports the deployment context.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quoting values safely

Use shell quoting when a value contains spaces or characters interpreted by the shell:

GREETING='Hello from production' pm2 start app.js

Do not put an unquoted value containing spaces after the equals sign; the shell will treat the remaining words as separate arguments. Values containing shell metacharacters require particularly careful quoting, and secrets should not be exposed in command history or process listings when your host’s operational policy prohibits that.

Update an existing process after an inline change

PM2 keeps the environment associated with a managed process. If you run a new command with a different assignment, an already-running application does not automatically receive the changed value. Include --update-env when restarting or reloading:

ENV_VAR=somethingnew pm2 restart my-node-app --update-env

The same flag applies to a reload:

API_URL=https://new-api.example.com pm2 reload my-node-app --update-env

Without the flag, the process can continue using the older value even though the shell command contains the new one. This conservative behavior is documented by PM2 for CLI-provided environment variables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the inline method is the right choice

  • Starting a local test with a temporary setting.
  • Applying a deployment value supplied by a shell script or host-level service.
  • Overriding one setting for a controlled restart without changing a shared configuration file.

Inline assignments are less suitable as the only record of a production configuration: they are easy to mistype, hard to review, and inconvenient when you maintain development, staging, and production variants.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Method 2: define variables in an ecosystem file

An ecosystem file gathers PM2 options and environment variables for one or more applications. Create a file such as ecosystem.config.js beside the project:

module.exports = {
  apps: [{
    name: "my-node-app",
    script: "./app.js",
    env: {
      NODE_ENV: "development",
      API_URL: "http://localhost:3000"
    },
    env_production: {
      NODE_ENV: "production",
      API_URL: "https://api.example.com"
    }
  }]
};

The env object is the default set of variables injected into the application. Named objects whose keys begin with env_ provide alternatives. In the example, env_production is selected with the name production.

Start the default environment

pm2 start ecosystem.config.js

This starts the application using the values in the env block.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start a named environment

pm2 start ecosystem.config.js --env production

The selector after --env must match the suffix exactly. Therefore --env production selects env_production, while --env staging would select env_staging if that block exists.

Add a staging block

module.exports = {
  apps: [{
    name: "my-node-app",
    script: "./app.js",
    env: {
      NODE_ENV: "development",
      API_URL: "http://localhost:3000"
    },
    env_staging: {
      NODE_ENV: "staging",
      API_URL: "https://staging-api.example.com"
    },
    env_production: {
      NODE_ENV: "production",
      API_URL: "https://api.example.com"
    }
  }]
};

Launch staging with:

pm2 start ecosystem.config.js --env staging

Keep the block names and command selectors consistent. A typo such as env_stage paired with --env staging will not select the block you intended.

Select one application from a multi-app file

An ecosystem file can declare several applications. When you need to operate on only one declaration, use PM2’s --only option with the application name:

pm2 start ecosystem.config.js --only my-node-app --env production

This avoids accidentally starting or restarting every application described in the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Applying edits to an ecosystem file

After changing an ecosystem file, restart or reload the application so PM2 launches workers with the new values:

pm2 restart ecosystem.config.js --env production
pm2 reload ecosystem.config.js --env production

PM2 documents that ecosystem-file environment changes are applied on pm2 restart or pm2 reload. Editing the JavaScript file alone does not mutate the environment of a process that is already running.

If the file contains multiple applications, target the intended one:

pm2 restart ecosystem.config.js --only my-node-app --env production

Use the same file path and application name that you used when starting the process. Running a command from another directory, or pointing at a second ecosystem file with a similar name, can make a correct edit appear ineffective.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choosing between the three configuration patterns

Method Best for Environment switching Updating a running app Repeatability
Inline CLI (NAME=value pm2 start) One-off starts or quick overrides Controlled by the shell command Restart or reload with --update-env Low unless scripted
Ecosystem env and env_* Shared defaults and checked-in app configuration env_<name> with --env <name> Restart or reload after editing the file High
External secret or platform injection Secrets and infrastructure-managed configuration Controlled outside the application file Depends on how the host exports values; PM2 receives the resulting process environment Medium to high

The first two rows are PM2 configuration mechanisms. External injection is an operational pattern: a deployment system or host secret store supplies variables before PM2 starts or reloads the process. PM2 does not turn that pattern into encrypted storage.

Using production and staging safely

Separate environment blocks make it harder to point a staging build at a production service by accident. Give each block complete, explicit values for settings that differ between environments:

module.exports = {
  apps: [{
    name: "orders-api",
    script: "./server.js",
    env_staging: {
      NODE_ENV: "staging",
      API_URL: "https://staging-api.example.com",
      LOG_LEVEL: "debug"
    },
    env_production: {
      NODE_ENV: "production",
      API_URL: "https://api.example.com",
      LOG_LEVEL: "info"
    }
  }]
};
  1. Verify the ecosystem file path and the application name.
  2. Choose the block with --env staging or --env production.
  3. Restart or reload after every configuration edit.
  4. Check application startup logs for the environment-specific behavior you expect.

Do not log full credentials or tokens while diagnosing an environment problem. If you need proof that a value is present, log a non-sensitive property such as whether it is defined, or log a redacted endpoint without query parameters and credentials.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Secrets, source control, and runtime injection

Plaintext production secrets in a repository can be copied by anyone who can read the repository, its history, backups, or build artifacts. Treat passwords, private keys, API tokens, and connection strings as secrets rather than ordinary application settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Keep secret values in the deployment platform or host’s secret-management process.
  • Inject them into the environment at runtime, then start or reload PM2.
  • Commit non-sensitive defaults and documented variable names, not production credentials.
  • Review shell history, CI logs, and startup output for accidental secret disclosure.

An ecosystem file can still describe non-secret values such as NODE_ENV or a public API endpoint. If a secret must be referenced by that file, arrange for the host or deployment process to provide it without committing the secret itself. The exact injection mechanism depends on your infrastructure; PM2 simply receives the environment that exists when it launches the process.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why process.env is undefined under PM2

“Undefined” can mean either that the variable was never supplied or that the application is reading a different name than the one you configured. Work through these checks in order.

Check the spelling and case

Environment names are case-sensitive on common Unix-like systems. API_URL, Api_Url, and api_url are different names. Compare the exact key in the command or ecosystem block with the key in process.env.

Confirm the command actually supplied the value

For an inline start, the assignment must appear before the PM2 command:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
API_URL=https://api.example.com pm2 start app.js

Writing pm2 start app.js API_URL=... does not create the same shell environment assignment. If a wrapper script is involved, make sure it exports the variable before invoking PM2.

Confirm the selected ecosystem block

pm2 start ecosystem.config.js uses the default env block. It does not select env_production automatically. Use --env production, and ensure the object is named exactly env_production.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Restart after changing configuration

A running process keeps the environment with which it was launched. Use pm2 restart or pm2 reload after an ecosystem edit. For an inline change, include --update-env on that restart or reload.

Verify the file and app entry point

When several projects or ecosystem files are present, you may be editing one declaration while PM2 is running another. Confirm the script path, current working directory, ecosystem filename, and application name. Use --only when a file defines multiple apps.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Remember that PM2 does not automatically parse every .env file

Putting API_URL=... in a file named .env does not, by itself, make PM2 load it. A separate environment-file loader or a Node runtime option must be configured for that behavior. Without such a setup, use the PM2 CLI assignment, an ecosystem env block, or your host’s runtime injection process.

A repeatable deployment workflow

The following workflow keeps configuration changes understandable and minimizes stale-process mistakes.

  1. Declare the variable contract. List required names such as DATABASE_URL, API_URL, and PORT. Decide which are public configuration and which are secrets.
  2. Validate at startup. Read required values through process.env and throw a clear error when one is absent or malformed.
  3. Choose the source. Use an inline assignment for a one-off operation, an ecosystem file for repeatable environment blocks, or host-managed injection for secrets.
  4. Start the intended app. Use the exact ecosystem path, script path, and application name. Add --env production or another selector when needed.
  5. Change values deliberately. Edit the ecosystem block or update the host’s exported environment. Do not assume a changed shell value alters an already-running process.
  6. Restart or reload. Add --update-env when the new value comes from a CLI assignment. A changed ecosystem file is applied on restart or reload.
  7. Inspect startup behavior. Check logs for the validation message or expected environment-specific configuration, while keeping secrets out of output.

Common failure modes and fixes

Symptom Likely cause Fix
process.env.MY_VARIABLE is undefined The name is misspelled, the variable was not supplied, or the wrong environment block was selected. Compare names exactly, select the matching env_* block, and validate at startup.
A new CLI value is ignored PM2 retained the environment of the existing process. Restart or reload with the assignment and --update-env.
An ecosystem edit is ignored The app was not restarted or the command targeted another file or app. Restart or reload the edited file, verify its path, and use --only for a specific app.
Production settings are not active --env production was omitted or the block suffix does not match. Use env_production with --env production.
A .env file has no effect PM2 is not an automatic parser for arbitrary .env files. Configure a separate loader or Node runtime option, or provide values through PM2 or the host environment.
The app starts, then fails while handling requests A required variable was missing or had an invalid type. Parse and validate values during startup, with an error naming the missing variable.

Practical command reference

# One-off start
API_URL=https://api.example.com pm2 start app.js --name my-node-app

# Update an existing process from the CLI
API_URL=https://new-api.example.com pm2 restart my-node-app --update-env

# Start the default ecosystem environment
pm2 start ecosystem.config.js

# Start a named environment
pm2 start ecosystem.config.js --env production

# Restart one app from a multi-app ecosystem file
pm2 restart ecosystem.config.js --only my-node-app --env production

# Reload after an ecosystem-file change
pm2 reload ecosystem.config.js --env production

What to remember

Use NAME=value pm2 start app.js for a quick, shell-controlled launch. Use an ecosystem file when configuration must be reviewable and when you need explicit development, staging, and production blocks. Read values with process.env.NAME, validate required settings before the server accepts traffic, and restart or reload after changes. Inline changes specifically require --update-env; ecosystem-file changes take effect on restart or reload. Keep production secrets in the host or deployment system and inject them at runtime rather than committing them to source control.

Frequently Asked Questions

Does PM2 automatically load a .env file?

No. A .env file has no effect merely because it exists. Configure a separate loader or Node runtime option, or provide the variables through PM2’s CLI, ecosystem configuration, or the host environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my changed inline variable not appear after pm2 restart?

PM2 uses conservative handling for CLI-provided environment values. Put the new assignment on the restart or reload command and add –update-env.

How do I choose staging instead of production?

Define an env_staging block and run pm2 start ecosystem.config.js –env staging. The selector must match the suffix after env_.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.