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 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, 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.