Search code examples
node.jsherokuenvironment-variables

Enviroment variables for production and development (heroku)



I have an app on Heroku (Node.js/Express + Postgres) and I want to use different databases for production and development. I know that I should use variables from process.env instead of hardcoded values inside my code. I think that I shouldn't use the if statement inside my code for checking if my environment is the production or local development.
For me, I should create 1 variable inside the .env file and then my server/environment should choose by itself which option is correct. (I mean that I should write check operator inside of .env file or have 2 different .env files and then bash script decides which to run.) So the question is:
Which way is the best for switching my process.env.DATABASE_URL depending on the environment I currently work in?
P. S. Maybe this is a stupid question, but I'm just trying to understand.


Solution

  • Ok, I think I got it. My code has a line with environment variable, i.e process.env.DATABASE_URL.

    Inside the .env file (which is ignored by Git) I'm setting DATABASE_URL to my_local_database_connection and using it in development. When I push it to Heroku I use config vars inside Heroku, which means that it "creates .env file" (or smth like this) from my config vars on the Heroku server and use that values on production.

    Also, as Big Person who commented on my question said, you can set your environment variables in a different way, you don't have to have .env file in your project, but it is a handy option.

    So in my code, I have only 1 line for both prod & dev. (The main idea is that I have the same var names for every environment)