0

how do i tell my node/ express app if it should use test.env or dev.env on mac?

I essentially want to be able to run my app and tell it which database to connect to; (dev or test). However the app always selects 'test.env'.

I am calling

process.env.DBNAME

in order to select the environment variable that stores my database name.

Would also be nice to know how to select the environment when I deploy my app in production.

I don't know what else to try and would really appreciate help!

  • You need to set the `.env` variable, and based on what the current environment is, read the variable's file. More details: https://stackoverflow.com/questions/22312671/setting-environment-variables-for-node-to-retrieve – Mostafa Fakhraei Jan 01 '23 at 19:37

1 Answers1

0

You can use the dotenv package as follows:

  1. Add a .env file and In your .env file, add variables for each environment:

    DB_URI_DEVELOPMENT="https://someuri.com"
    DB_USER_DEVELOPMENT=someuser
    DB_PASSWORD_DEVELOPMENT=somepassword
    
    DB_URI_TEST="https://otheruri.com"
    DB_USER_TEST=otheruser
    DB_PASSWORD_TEST=otherpassword
    
  2. Start the application in development:

NODE_ENV=development node server.js

or in test:

NODE_ENV=test node server.js

Access the environment variables in your app:

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}


const env = process.env.NODE_ENV.toUpperCase();

Access the environment variables for the current environment by postfixing them with the uppercase environment string.

 var dbUri = process.env['DB_URI_' + env];
 var dbUser = process.env['DB_USER_' + env];
 var dbPassword = process.env['DB_PASSWORD_' + env];
Hrusikesh
  • 185
  • 9