7

I am currently building a backend in nodejs. I am thinking about how to add an environment configuration to the project. My idea is that I have a /config folder in which I have my envparser.ts (have to think about a better name for this ^^) which interprets my .env files to use them as regular javascript const. By using scripts in my package.json I would like to have the ability to switch the envs. But I don“t know how to switch between multiple .env files using dotenv.

File structure:

config/
   .env.development
   .env.production
   envparser.ts

Scripts:

yarn start
yarn start -p/-production //Or a different Syntax to change envs
Masdot
  • 90
  • 1
  • 7

3 Answers3

12

You can use dotenv package for accessing ur .env.* files.


You can switch between different environments by changing the NODE_ENV variable using the different started commands in package.json

For eg:

"scripts": {
    "start": "NODE_ENV=development nodemon index.js",
    "deploy": "NODE_ENV=production node index.js"
}

And then, u can access them in your index.js file as :

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })
Himanshu Singh
  • 1,803
  • 3
  • 16
5

You can have something like this in your scripts section in package.json

"start:dev": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.development", 
"start:prod": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.production"

start server in DEV mode by running npm run start:dev

start server in PROD mode by running npm run start:prod

Community
  • 1
  • 1
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
0

You can have something like this in your scripts section in package.json:

"dev": "nodemon -r dotenv/config index.js"

Tyler2P
  • 2,324
  • 26
  • 22
  • 31