Node.js: Using the dotenv library

This documentation is part of the Handle secrets guide. View the full guide here: How to handle secrets with Node.js.

👋 Welcome to the Stackhero documentation!

Stackhero delivers a ready-to-use Node.js cloud environment designed to help you move faster:

  • Deploy to production in seconds with a simple git push. No extra tooling or manual setup is required.
  • Bring your own domain and benefit from automatic HTTPS certificates, keeping your application secure without extra configuration.
  • Automatic backups, one-click updates, and predictable pricing help you focus on shipping features, and Stackhero manages the infrastructure for you.
  • Built on private, dedicated infrastructure for consistent performance and strong security.

Save time and reduce operational overhead: you can have your application running on Stackhero's Node.js cloud hosting in just a few minutes.

In real-world projects, you often need to manage multiple secrets. For example, connecting to a database may require a hostname, username, and password.

Handling a single secret is simple, but juggling several can quickly become awkward. 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 quickly becomes hard to read and maintain. In production, you might need even more variables, making this approach impractical.

That is where the dotenv library can help.

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

To get started, you can install the dotenv library by running:

npm install dotenv

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

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

To keep your secrets safe, make sure 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 reads your .env file automatically on your development machine. In production, you do not need the .env file. Environment variables are pulled directly from your Node.js service configuration, which you can manage through the Stackhero dashboard.