Node.js: Using the dotenv library

This documentation is part of the Managing secrets guide. You can view the complete guide here: How to manage secrets with Node.js.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Node.js cloud solution that provides a host of benefits, including:

  • Deploy your application in seconds with a simple git push.
  • Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
  • Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
  • Get optimal performance and robust security thanks to a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Node.js cloud hosting solution!

In real-world projects, it is common to need to manage several secrets. For example, connecting to a database often requires a hostname, username, and password.

Managing a single secret is simple, but juggling several quickly becomes cumbersome. Imagine starting your application with a command like this:

POSTGRESQL_HOST=<XXXXXX>.stackhero-network.com POSTGRESQL_USER=admin POSTGRESQL_PASSWORD=myPassword node app.js

This soon becomes difficult to read and maintain. In production, you will likely have even more variables, making this approach impractical.

This is where the dotenv library comes in.

With dotenv, you can store your secrets in a separate file called .env.

To get started, install the dotenv library by running:

npm install dotenv

Next, create a .env file to store your variables:

POSTGRESQL_HOST=<XXXXXX>.stackhero-network.com
POSTGRESQL_USER=admin
POSTGRESQL_PASSWORD=myPassword

To keep your secrets secure, ensure your .env file is not added to your Git repository. You can do this by adding it to your .gitignore file:

echo ".env" >> .gitignore

Finally, load the dotenv library at the top of your app.js file:

require("dotenv").config();

With this setup, when you start your application using node app.js, dotenv automatically reads your .env file on your development machine. In production, you do not need the .env file. Environment variables are retrieved directly from your Node.js service configuration, which you can manage via the Stackhero dashboard.