How do you detect what environment an expressJS app is running in? (development, test, production?). There\'s nothing in process.env
indicating an environment..
There are a lot of useful recommendations in other answers. I'm generally doing it like this:
const environment = process.env.NODE_ENV || 'development';
The good thing is that such approach is not specific to Express per se, but actually is an accepted practice in wider Node.js ecosystem.
Also, 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
.
Please see more details and use cases on the detect-environment's page.
You can either check the environment by checking the app.settings.env
(this will work in Express), or you can do it in a more direct way by checking process.env.NODE_ENV
(the environment is the one found in that variable or 'development' by default < this also works in other libraries such as Socket.IO etc).
app.get('env') would also return the environment.
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}
I'd like to address a straightforward way to passing NODE_ENV variables to your node script in order to access them in process.env
"scripts": {
"start": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon server.js",
"debug": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon --debug server.js",
"test": "./node_modules/.bin/cross-env NODE_ENV=test ./node_modules/.bin/babel-tape-runner test/test-*.js"
},
can be used as
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}
The can detect which environment you are in by inspecting app.settings.env
.
cannot access the nodejs server. can detect node env from express using app.setting.env
var app = express();