Accessing NODE_ENV at runtime in the server.js configuration of Sails.js

node.js, sails.js

Solution

run your application like this instead:

NODE_ENV=production node app.js

or

sails lift --prod

in the application root directory. the command line switch you're trying to use is meant to be passed to the sails executable, not directly to your application javascript.

Problem

I find myself not able to access the NODE_ENV variable when trying to make config changes in the `config/server.js` file of Sails.js. I want to configure the `serverOptions` flag of the `express` property and bind ssl certificates - but only for production. Assuming I started the server with `node app.js --prod` This doesn't work: ``` module.exports = { ... }; console.log(process.env.NODE_ENV); // undefined ``` But this does work: ``` module.exports = { ... }; setTimeout(function () { console.log(process.env.NODE_ENV); // production }, 1000); ``` Basically all I want to do is: ``` module.exports = (function () { var env = process.env.NODE_ENV, ret = { express: {} }; if (env == 'production') { ret.express.serverOptions = { key: ..., cert: ... }; } return ret; }()); ``` I've seen similar answers like https://stackoverflow.com/a/21152780/986408 but I can't understand how they should work when mine doesn't.

Original source