Search code examples
node.jstypescriptecmascript-6dotenv

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


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

Solution

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