Home > database >  How to use different environments with `.env` files in NodeJs
How to use different environments with `.env` files in NodeJs

Time:04-18

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

CodePudding user response:

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}` })

CodePudding user response:

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 npm run start:dev

start server in PROD mode by nom run start:prod

  • Related