How to toggle between multiple .env files like .env.development with Node.js?

Sometimes, we want to toggle between multiple .env files like .env.development with Node.js.

In this article, we’ll look at how to toggle between multiple .env files like .env.development with Node.js.

How to toggle between multiple .env files like .env.development with Node.js?

To toggle between multiple .env files like .env.development with Node.js, we can use the dotenv package.

To install it, we run

npm i dotenv

Then we use it by writing

require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` });

to require the dotenv module.

Then we call config with an object with the path set to the path of the config file we want to use.

Conclusion

To toggle between multiple .env files like .env.development with Node.js, we can use the dotenv package.