6

I am setting a variable in Express.js as follows: app.set('HOST', 'demo.sample.com');. However, if I try to read this variable, I get undefined as the output. I am reading the variable using process.env.HOST. Nevertheless, if I try to read it using app.get('HOST'), I get the correct value.

I cannot use app.get('HOST') since I am reading the variable in another file too — a file that does not contain a reference to the Express.js app variable.

How do I get the value using process.env.HOST?

3 Answers 3

6

app.set() doesn't set environment variables, it's just a convenience method offered by Express to be used together with app.get().

If you want to set an environment variable in your JS code, use this:

process.env.HOST = 'demo.sample.com';
Sign up to request clarification or add additional context in comments.

3 Comments

So do you mean to say that app.set and process.env do not work in conjuction with each other?
Oh, I skipped that part. Disregard my answer then. process.env is not related to Express at all, it reads system variables.
Just wanted to add my twocents on this : I wanted to get an "if on heroku" so I did this : if(process.env.NODE_ENV == 'production') {} Using expressjs
1

Update: process.env only reads your operating system environment settings. To setup express vars, use app.get() and app.set(), like in the other answer.

Is your HOST variable set at all? It's usually set as HOSTNAME.

[zlatko@droplet ~]$ node
> process.env.HOST
undefined
> process.env.HOSTNAME
'droplet.zlayer.net'
>

You could set it manually in Bash (I assume you use bash) though:

[zlatko@droplet ~]$ export HOST=$HOSTNAME
[zlatko@droplet ~]$ node
> process.env.HOST
'droplet.zlayer.net'

>

The export line could have been a literal, ie:

export HOSTNAME=myhostname.myserver.com

1 Comment

actually, host here is just an example. I have other variables too that are specific to my project and they are not set too. So host or hostname does not matter.
0

If you are on Linux you will need to set the environment variable for the bash/shell in order to call it from the APP. Try setting the environment variable using export NODE_ENV='production' or 'development' then configure your app using app.configure 'production',() -> and try again

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.