Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variables in .env file in node.js app heroku

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.

like image 260
xerotolerant Avatar asked Jan 18 '26 02:01

xerotolerant


1 Answers

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.

like image 130
Michał Młoźniak Avatar answered Jan 20 '26 16:01

Michał Młoźniak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!