karivool
karivool

Reputation: 43

Heroku config vars not accessible in node.js?

I have a couple of config vars set up in Heroku: baseURL, NODE_ENV and PROD_MONGODB.

However, trying to access the config var baseURL in my app, it comes up undefined.

Doing console.log(process.env); to see what vars are available gives me this:

{NODE_ENV: "development", PUBLIC_URL: ""}

Why don't some of the vars I set up for Heroku show up or are accessible? Am I missing something obvious?

Upvotes: 3

Views: 4309

Answers (2)

nomadj
nomadj

Reputation: 31

Without seeing any of your code, assuming you set the config vars properly, and assuming you are trying to access them via the web and not through your localhost, I would guess that you are attempting to access the config vars client-side. You must bring them in server-side, then distribute them accordingly on the client end.

Upvotes: 0

Mo Hemati
Mo Hemati

Reputation: 281

the problem is that you have set Heroku config vars and it's all good for your production but your local app doesn't have access to those config vars. you need to create another .env file for your local environment vars.

  1. On the root of your project create a folder and call it config
  2. under config folder create a file and name it dev.env
  3. you can set your environment variables here with key=value structure.
  4. add config to your .gitignore file

for example, by setting up PORT=3000 in the dev.env file, you can have access to port 3000 when running your app locally and also have Heroku set its port to whatever it likes to be. Within your app, you only need to use process.env.YOUR_KEY which in this example will be process.env.PORT.

setting up environment vars can be a huge pain as every operating system has it's on way. you can use a npm node module env-cmd to overcome this problem. first, install it as a development dependency by:

npm i env-cmd --save-dev

now open your package.json file and the blow script to use it on your development:

"scripts": {
    "start": "node src/app.js",
    "dev": "env-cmd ./config/dev.env nodemon src/index.js"
  }

I have assumed that you're using nodemon and you have an index.js file in your src directory.

you can take a look at this answer for Heroku config vars if you need. https://stackoverflow.com/a/55233621/7274342

Upvotes: 3

Related Questions