Categories
Node.js Quick Tips Quick Tips

Only use dotenv in development

< 1 min read

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:

  1. npm install --save-dev dotenv – Install it as a development dependency. This typically means it won’t get deployed to production.
  2. Add a script to the scripts section of your package.json file which preloads the dotenv module and runs your application e.g. "start": "node -r dotenv/config server.js"
  3. 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.

Original tweet

Leave a Reply

Your email address will not be published. Required fields are marked *