46

The command I run on my server to start my node app is:

sudo IS_PROD=1 node app.js

I have forever installed but can't seem to pass in the environment variable.

sudo IS_PROD=1 forever node app.js

Doesn't seem to do the trick. I have tried several varieties of this. How do I either execute this command successfully or permanently set the environment variable?

user1168427
  • 1,003
  • 3
  • 10
  • 16

2 Answers2

98

First of all you should skip the node thing in you command, it should not be there, you should not be able to execute that. automatically starts your script using . Instead you should do like this;

sudo IS_PROD=1 forever app.js

Probably you, instead of starting your server in foreground, will want to start your server as a daemon. eg.

sudo IS_PROD=1 forever start app.js

This will create a process in the background that will watch your node app and restart it when it exits. For more information see the readme.

Both of these methods preserves the environment variables, just like when you are just using node.

Mattias
  • 9,211
  • 3
  • 42
  • 42
  • 1
    I've got a small question, as i assume this env var is preserved on each server restart made by forever, can i somehow pass a different variable for the case of restart, not first startup. I just want do make some filewritings on first startup (Uglifying) and than do not repeat it on restarts. – Max Yari May 09 '15 at 14:51
  • 1
    True. It was my issue. I simply didn't enter `start`. *WRONG*: `NODE_ENV="production" forever bin/www`. *CORRECT*: `NODE_ENV="production" forever start bin/www` – Green Jun 27 '16 at 05:14
18

app.js:

console.log(process.env.IS_PROD);

Using node (v0.8.21)

$ node app.js
undefined

$ IS_PROD=1 node app.js
1

$ sudo IS_PROD=1 node app.js
1

Using forever (v0.10.0)

$ forever app.js
undefined

$ IS_PROD=1 forever app.js
1

$ sudo IS_PROD=1 forever app.js
1

Documentation:

process.env

An object containing the user environment. See environ(7).

Community
  • 1
  • 1
mak
  • 13,267
  • 5
  • 41
  • 47