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.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

PM2 accepts environment variables in two practical ways: assign them inline when you start or update an app, or define them in an ecosystem file. Your Node.js code reads either method through process.env. For a one-off launch, use NAME=value pm2 start app.js. For repeatable deployments and separate development, staging and production values, use env and named env_* blocks in an ecosystem file.

The important update rule is easy to miss: a changed inline shell value is not automatically copied into an already managed process. Restart or reload with --update-env. Values changed in an ecosystem file are applied when you restart or reload the app.

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

Two supported ways to inject variables

PM2 starts your Node.js process with an environment inherited from the command that launches it or from the configuration in an ecosystem file. In application code, access a value by its exact name:

const endpoint = process.env.API_URL;

Choose the method according to how often the value changes and whether more than one environment must be reproducible.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
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 the command is scripted
Ecosystem env Shared defaults and checked-in app configuration Use an env_<name> block with --env <name> Restart or reload after editing the file High
External secret or platform injection Secrets and infrastructure-managed configuration Controlled outside the app file Depends on how the host exports values; PM2 receives the resulting process environment Medium to high

The third row is an operational pattern rather than a separate PM2 configuration feature. A deployment system or host exports the variables, and PM2 starts the process with those values.

Pass variables on a one-off PM2 start

Start an app with an inline assignment

Put the assignment immediately before the PM2 command:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ENV_VAR=value pm2 start app.js

For example:

API_URL=https://api.example.com pm2 start app.js

PM2 starts app.js with API_URL available to the Node.js process. Read it in the application as process.env.API_URL:

const apiUrl = process.env.API_URL;

This style is useful for a temporary test, a manual launch, or a quick override when you do not need a checked-in configuration file. It is less suitable as the main deployment record because the values live in shell history, deployment scripts or operator notes rather than in one PM2 application definition.

Use more than one variable

Place each assignment before the command, separated by spaces:

NODE_ENV=production API_URL=https://api.example.com pm2 start app.js

The application receives both names. Names are case-sensitive, so API_URL and api_url are different variables. Keep the spelling in the shell command, application code and any ecosystem file identical.

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

Update an existing process after changing a CLI value

PM2 deliberately treats environment inherited from the CLI conservatively. If an app is already managed and you run a new command with a different value, the process can continue using the old value. Apply the changed value during a restart or reload with --update-env:

ENV_VAR=somethingnew pm2 restart app --update-env

Use the same pattern for a reload:

ENV_VAR=somethingnew pm2 reload app --update-env

The option matters because restarting without it may leave the managed process with the environment it already held. PM2 documentation describes this behavior as conservative: newly supplied CLI variables are not updated into the application during a normal restart, reload, stop or start unless you request the environment update.

Use an ecosystem file for repeatable configuration

Create the configuration

An ecosystem file gathers the PM2 options and environment variables for one or more applications. A minimal file named ecosystem.config.js can define a default environment and a production environment:

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 injected into the application. The env_production object is a named alternative. PM2 merges the selected configuration into the process environment when it starts the app.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Start the default block

Run:

pm2 start ecosystem.config.js

This starts the app using the values in env. In the example, the process receives NODE_ENV=development and the local API URL.

Select a named environment

Choose the production block with:

pm2 start ecosystem.config.js --env production

The selector name must match the suffix exactly: --env production selects env_production. A staging setup follows the same convention:

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"
    }
  }]
};

With this arrangement, the environment name is explicit in the command and the values remain reviewable in one file. Add a new block only when that environment has a distinct, intentional configuration.

Manage several applications in one file

The apps array can contain multiple application definitions. Give each a distinct name and the correct script. When a file declares several apps, select the intended one with PM2’s --only option from the ecosystem-file workflow. This prevents an environment change intended for one service from being applied to every service in the file.

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

How environment changes are applied

Changes made in an ecosystem file

Edit the relevant env or env_* object, then restart or reload the app managed from that ecosystem file. PM2 states that ecosystem-file environment values are updated on pm2 restart or pm2 reload.

For example, changing API_URL in env_production does not alter a process that is currently running until that process is restarted or reloaded. Make sure you edit the same ecosystem file and app definition that PM2 is using.

Changes supplied by the shell

For CLI assignments, include --update-env on the restart or reload command. The assignment and option belong on the same command so PM2 can import the new value:

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

Without the option, checking the shell variable alone does not prove that the already managed Node.js process changed.

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

Configure production and staging safely

Keep selectors and block names aligned

PM2 uses the text after --env to find a block named env_ plus that text. These pairs align:

  • env_production with --env production
  • env_staging with --env staging

A spelling or capitalization mismatch means PM2 cannot select the intended block. Treat the suffix as an exact identifier, not a descriptive label.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Separate defaults from deployable environments

Use env for the default developers should receive when no selector is supplied. Put staging and production endpoints in their named blocks so a plain start does not silently point at a remote service. Give each block a complete, deliberate set of values rather than relying on an operator to remember an additional shell assignment.

Switch deliberately

Before starting or restarting for a deployment, verify three things:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. The ecosystem file path is the intended one.
  2. The application name and script identify the intended service.
  3. The selector exactly matches the desired env_* block.

Then use the PM2 start or restart/reload workflow for that app. If several applications share a file, use --only when the operation should affect just one of them.

Read and validate variables in Node.js

Access the injected value

Read a variable through process.env at the point where your application needs it:

const apiUrl = process.env.API_URL;
console.log(`Using API endpoint: ${apiUrl}`);

The variable name must match the PM2 configuration exactly. A typo in either place results in a missing value from the application’s perspective.

Remember that environment values arrive as strings

Environment variables are represented as text. If application logic needs a number or a boolean, convert and validate it in your startup configuration rather than assuming JavaScript has already performed the conversion. Keep the original key name in the PM2 command or ecosystem object, and make the conversion decision in one clearly documented place in the application.

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.

Fail clearly when a required value is absent

For values the app cannot operate without, validate them during startup instead of allowing an obscure downstream error:

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

const apiUrl = requireEnv("API_URL");

This validation is an application-level safeguard. PM2 injects the environment; it does not decide which variables are mandatory for your business logic. A clear startup error also tells you whether the issue is configuration rather than an API connection or routing failure.

Verify the selected configuration without exposing secrets

When diagnosing a deployment, log the names of non-sensitive settings or a deliberately safe value such as the selected environment and endpoint host. Do not print passwords, tokens or complete credential values into application logs. A startup check that reports a missing key, while redacting its value, is more useful than dumping the entire environment.

Do not assume PM2 loads a .env file

PM2’s documented mechanisms here are inline CLI assignments and ecosystem-file blocks. Do not assume that placing a file named .env beside your application automatically populates process.env under PM2. If your project uses a separate environment-file loader or a Node.js runtime option, configure that mechanism explicitly and verify it independently. Otherwise, define the values in the ecosystem file or inject them from the host before PM2 starts the process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Keep secrets out of committed configuration

An ecosystem file is convenient for repeatable non-secret settings such as NODE_ENV and an endpoint. Plaintext production credentials in a public repository create a separate operational risk. Use the deployment platform or host’s secret-management process to export sensitive values at runtime, then start PM2 with that environment.

This pattern does not mean PM2 encrypts ecosystem files. PM2 receives whatever the launching environment provides. Protect the source of the variables, access to the host and any deployment logs or scripts that might expose them. Keep only safe defaults and non-sensitive routing information in a file that is intended to be reviewed or committed.

A deployment sequence that avoids stale configuration

For a repeatable release, first identify the exact ecosystem file and app name that represent the service. Review the intended env_* block, confirm its selector, and check that secrets will be exported by the host or deployment system rather than copied into source control. Start with pm2 start ecosystem.config.js --env production for a new process, or restart/reload the named app after an edit. If the value came from a shell assignment instead of the file, include --update-env on that same restart or reload command.

After the operation, let the application perform its startup validation. A missing-key error points to injection, naming or block selection; an application-level connection error means the value was present but may point to the wrong service. This separation makes rollback and incident diagnosis more predictable without requiring the application to print sensitive values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot missing or stale values

process.env is undefined

  • Confirm the variable name in application code exactly matches the CLI assignment or ecosystem key.
  • Confirm PM2 started the intended script, not a different entry point.
  • If using an ecosystem file, verify that you started that file and selected the expected block.
  • Restart or reload after changing the configuration.

For a required setting, startup validation should produce the missing variable’s name, making a spelling or selection error easier to locate.

The old value remains after a CLI change

Use the changed assignment together with --update-env:

NEW_VALUE=updated pm2 restart my-node-app --update-env

A normal restart without the option can preserve the environment already held by PM2’s managed process.

The production value is not being selected

Check that the file contains env_production and that the command uses --env production. The suffix must match exactly. If you intended staging, use env_staging and --env staging instead.

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

An ecosystem edit has no effect

Restart or reload the app after saving the file. Then verify that the command references the edited ecosystem file and the correct app. When multiple apps are declared, use --only to target the service you changed.

A secret appears in source control

Remove the plaintext value from the committed configuration, rotate the exposed credential through the relevant service, and move injection to the host or deployment platform’s secret process. Keep the PM2 file limited to values that are safe for the repository’s audience.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Practical choices and common pitfalls

Inline assignments are fast but easy to lose: a later operator may not know which shell command originally supplied the value, and shell history or deployment logs can retain sensitive text. Ecosystem files make the selected environment and endpoint visible for review, but they must be protected when they contain anything confidential. Host-managed injection keeps secrets outside the application definition, yet the deployment process must reliably export those values before PM2 starts or updates the app.

Do not mix methods accidentally. For example, an operator may edit env_production while a running process was originally started with a CLI override. Decide which source is authoritative, then restart or reload using that source. Similarly, changing a file on disk is not the same as changing a running process; the process receives its environment at startup or update time.

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

When several services share one ecosystem file, confirm both the app selector and the environment selector. A correct production block applied to the wrong script is still an outage. Keep names distinct, use --only for a single service, and make startup validation part of every service so configuration mistakes fail early.

A practical operating checklist

  1. Choose inline CLI assignment for a temporary or one-off launch; choose an ecosystem file for repeatable operation.
  2. Use the exact variable name your Node.js code reads through process.env.
  3. For multiple environments, create blocks such as env_staging and env_production.
  4. Select a block with --env <name>, matching the suffix exactly.
  5. After a CLI value changes, restart or reload with --update-env.
  6. After an ecosystem value changes, restart or reload the affected app.
  7. Check the ecosystem path, script, app name and, when needed, --only.
  8. Validate required variables during application startup.
  9. Inject production secrets through the host or deployment platform rather than committing plaintext credentials.
  10. Do not rely on automatic .env parsing unless you have separately configured a loader or Node.js runtime option.

What to remember

For a quick start, write NAME=value pm2 start app.js and read the result as process.env.NAME. For a durable setup, put defaults in env and environment-specific values in blocks such as env_production, then select one with --env production. The update behavior determines whether your change is visible: CLI assignments require --update-env on restart or reload, while ecosystem-file edits take effect when the app is restarted or reloaded. Explicit validation and deliberate secret injection turn those mechanics into a reliable deployment process.

Frequently Asked Questions

How do I pass an environment variable when starting a Node.js app with PM2?

Put the assignment before the command, for example API_URL=https://api.example.com pm2 start app.js. Read it in Node.js as process.env.API_URL.

Why did PM2 keep my old value after I changed the shell variable?

CLI-provided environment is conservative. Restart or reload with the new assignment and --update-env, such as API_URL=https://new-api.example.com pm2 restart my-node-app --update-env.

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

How do I configure production and staging values?

Define env_staging and env_production objects in an ecosystem file, then run with --env staging or --env production. The suffix must match exactly.

Do ecosystem-file changes apply immediately?

No. Save the edited file, then restart or reload the affected PM2 app. PM2 applies the updated environment during that operation.

Why is process.env.MY_VARIABLE undefined?

Check spelling and capitalization, the script PM2 started, the ecosystem-file path, and the selected environment block. Restart or reload after correcting the configuration.

Does PM2 automatically load a .env file?

Do not assume so. Use an explicitly configured environment-file loader or Node runtime option, or define the values in the ecosystem file or host environment.

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

Where should production secrets be stored?

Keep plaintext credentials out of committed ecosystem files. Have the deployment platform or host’s secret process export them at runtime before PM2 starts or updates the app.

How can I update only one app in a shared ecosystem file?

Give each app a distinct name and use PM2’s --only option to target the intended service.

The Bottom Line

Use NAME=value pm2 start app.js for a one-off launch, and use an ecosystem file with env plus env_* blocks for repeatable staging and production configuration. Apply changed CLI values with --update-env; restart or reload after ecosystem edits. Validate required keys in Node.js and inject secrets from the host or deployment platform instead of committing them.

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.

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