3

I declared variables in a file named .env

MONGOCONNECTIONSTRING=connectionstring

when I run heroku local web it says

[OKAY] Loaded ENV .env File as KEY=VALUE Format

I am trying to use the environment variables like this

const connectionString = process.env.MONGOCONNECTIONSTRING

in my index.js file

when I try to print the variable connectionstring it is undefined. How do I access the variables.

Heroku's best practices say to do that however I must be missing something since the variables are never available.

2
  • Did you find a solution? I have the same problem Commented Aug 13, 2017 at 9:55
  • Hey. I did. I think I used a package called dotenv. I'll check that app and get back to you in a few. Commented Aug 13, 2017 at 11:51

2 Answers 2

4

The general practice on Heroku is that you configure your application by setting config vars either via Heroku Dashboard or CLI command. Using CLI is recommended because you can set multiple variables at once:

heroku config:set MONGOCONNECTIONSTRING=connectionstring

.env file should be used only for local development and you shouldn't commit this file to the repository. It is actually mentioned in the docs that you linked.

Also I wonder if you have MongoDB addon provisioned on Heroku? If so, it should set appropriate connection string automatically. Maybe you should check the docs for that.

Sign up to request clarification or add additional context in comments.

8 Comments

I am still testing the node app during development. I am trying to connect to a remote mongodb server when I run heroku local.
Ahh, sorry, I misunderstood your question. And how does your Procfile look like?
web: node dist/index.js This is the only thing in it to point to the startup file for the app.
You can try to output all env variables to see if anything is there console.log(process.env). You can also try to export this variable with export MONGOCONNECTIONSTRING=connectionstring or just run MONGOCONNECTIONSTRING=connectionstring node dist/index.js.
Printing the process.env to the console shows the environment variables for my windows computer. I copied it out and it does not contain what I entered in that file. I guess I could put it there in the proc file but wouldn't that defeat the purpose of having the environment variable altogether? The procfile would end up in my version control.
|
2

I found out the issue. The .env file was not encoded in UTF-8, so the parsing was wrong.

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.