Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 launch.json:

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

In Node's package.json:

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

In Webpack's webpack.config.js:

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

While running the code:

set NODE_ENV=production && node app

NPM packages:

https://www.npmjs.com/package/envify

Powershell:

$env:NODE_ENV="production"

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?

like image 698
Chron Bag Avatar asked Jun 13 '16 19:06

Chron Bag


1 Answers

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.

like image 102
peteb Avatar answered Sep 21 '22 14:09

peteb