Chron Bag Chron Bag - 2 years ago 200
Node.js Question

Confused by how many ways there are to set NODE_ENV

I'm trying to set a flag that informs my code whether it is in production or development. So far I've seen:

In VS Code's


{ "configurations": { "env": "NODE_ENV": "development" } }

In Node's

{ "scripts": { "start": "NODE_ENV=production" } }

In Webpack's

module.exports = { "plugins": new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }) }

While running the code:

set NODE_ENV=production && node app

NPM packages:



I guess I'm just confused because by default I have around 4 of those set currently. How exactly do these interact? Are they all referring to the same variable? Should I only have one of these? Which ones overwrite the others?

I'd really prefer if there were just a single point to set this because it seems like every single module lets you specify it and as a result, I'm confused as to where it is actually being set. Also, is there anyway to access this flag on the client-side as well or is it server-side only?

Answer Source

In the scenario you've specified, the NODE_ENV environment variable will be initialized by the process that is actually executing your code. See the below excerpt from the environment variable wikipedia.

In all Unix and Unix-like systems, each process has its own separate set of environment variables. By default, when a process is created, it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child. At the API level, these changes must be done between running fork and exec. Alternatively, from command shells such as bash, a user can change environment variables for a particular command invocation by indirectly invoking it via env or using the ENVIRONMENT_VARIABLE=VALUE <command> notation. All Unix operating system flavors, DOS, and Windows have environment variables; however, they do not all use the same variable names. A running program can access the values of environment variables for configuration purposes.

So if you were to run your code using pm2, then pm2 will actually assign the NODE_ENV environment variable prior to executing your application. It uses a JSON file for options where you can specify your environment variables using the env property.

In short, all the ways to set your NODE_ENV are more or less equivalent, it just boils down to who starts your process.

Since environment variables are local to a machine (the environment) they are set locally and can't be set by a client.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download