Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS, detect production environment

When I'm in dev mode I don't want my server to send email and some other stuff so I have this in server.js file:

process.env.NODE_ENV = 'development';

When I move it to production i change the value to 'production'.

Problem is of course that it is easy to forget on deployments. Is it possible somehow to detect when server is in production?

If it's not, is it possible to write a batch script that replaces a string in a file?

like image 396
Joe Avatar asked Jan 23 '15 13:01

Joe


2 Answers

You shouldn't manually change values of process.env object, because this object is reflecting your execution environment.

In your code you should do the following:

const environment = process.env.NODE_ENV || 'development';

And then you launch your app in production like this:

$ NODE_ENV=production node app.js

If NODE_ENV environment variable is not set, then it will be set to development by default.

You could also use dotenv module in development to specify all environment variables in a file.

Furthermore, I've implemented a reusable module, which allows to automatically detect environment by analyzing both CLI arguments and NODE_ENV variable. This could be useful on your development machine, because you can easily change environment by passing a CLI argument to you Node.js program like this: $ node app.js --prod. It's also nice to use with Gulp: $ gulp build --prod.

Please see more details and use cases on the detect-environment's page.

like image 104
Slava Fomin II Avatar answered Sep 18 '22 07:09

Slava Fomin II


The suggested way to tackle these kind of problems is by using the process global object provided by NodeJS. For example:

var env = process.env.NODE_ENV || "development";

By the above line. We can easily switch between development / production environment. If we haven't configured any environment variable it works with development environment.

process.env is an object that contains the user environment.

For example if we are running our application in a bash shell and have configured NODE_ENV to production. Then i can access that in node application as process.env.NODE_ENV.

There are multiple ways to define this NODE_ENV variable for nodejs applications:

## Setting environment variable for bash shell
export NODE_ENV=production

## Defined while starting the application
NODE_ENV=production node app.js

So i don't think you would require any batch file for this. When handling multiple configuration variables, follow this.

like image 26
Samar Panda Avatar answered Sep 19 '22 07:09

Samar Panda