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 designed to help you move faster:
- Deploy to production in seconds with a simple
git push. No additional tools or manual configuration needed.- Use your own domain and take advantage of automatic HTTPS certificate setup, keeping your application secure with no extra steps.
- Enjoy automatic backups, one-click updates, and predictable, transparent pricing so you can focus on building features while Stackhero manages the infrastructure.
- Benefit from dedicated, private infrastructure for optimal performance and enhanced security.
Save time and simplify your operations: 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 usually 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 quickly becomes hard to read and maintain. In production, you will likely have even more variables, making this approach impractical.
That 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, 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 automatically reads your .env file 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.