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
scriptssection of your
package.jsonfile which preloads the
dotenvmodule and runs your application e.g.
"start": "node -r dotenv/config server.js"
And you’re done! No more
dotenv in production ✨
dotenv documentation provides examples of how you can configure it when using the preload approach, and you can read about the node
--require-module command line option in the Node.js documentation.