The dotenv library is a popular way of loading configuration for your Node.js application from an .env
file in development. You shouldn’t need it in production though as most hosting providers (e.g. Digital Ocean, Heroku, AWS) provide their own mechanism for you to safely inject environment variables into the environment that your application is running in.
You can avoid the need to require dotenv
in your application, and keep it as one of your devDependencies
, by using the "preload" approach:
npm install --save-dev dotenv
– Install it as a development dependency. This typically means it won’t get deployed to production.- Add a script to the
scripts
section of yourpackage.json
file which preloads thedotenv
module and runs your application e.g."start": "node -r dotenv/config server.js"
- Run
npm start
And you’re done! No more dotenv
in production ✨
The dotenv
documentation provides examples of how you can configure it when using the preload approach, and you can read about the node -r
/ --require-module
command line option in the Node.js documentation.