How to use environment variables with Node.js – dotenv tutorial
Dotenv is a zero-dependency module that loads environment variables from a .env
file into process.env
. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology. (Source – Npm.js)
Environment variables are variables external to our application that resides in the OS or the container of the app is running in. Typically, our applications require many variables. By separating our configurations, our application can easily be deployed in a different environment and we won’t have to change the application code and then having to rebuild it.
By convention, the variables are capitalised example: “DB_NAME” and the values are strings. Simply put, an environment variable is simply a name mapped to a value – “NAME=VALUE”. For example:
DB_HOST=localhost DB_USER=root DB_PASS=rad123
The most common use of .env file is to store:
- Database Connection Details
- Execution Mode (Development, Prodution, Stagging, etc.)
- API Endpoints – External services
- Application Key’s
- Paths / Location
- Port numbers
Creating Hello World App
Let’s explore how we can put dotenv into practice. First, let’s start by creating a new “Hello World” application.
Let’s start by creating a new Node.JS Project. To do that, create a new project folder and then run the following command in Command Line (Mac / Linux) or Powershell (Windows).
npm init
This will initialise a new project for you and itβs going to ask you a few questions about your project. The most important one is to give your package a name and then you can just keep pressing enter until the installation is over.
You can skip all questions by adding the “-y” flag like in the example below:
npm init -y
At this point, you should see a file called package.json in your project folder.
Dependencies Installation
The only dependency that we need for this project is dotenv. This time we will start the server manually as we won’t be making too many changes to the code.
[x] dotenv
Open the Command Line / Terminal / Powershell and install dotenv:
npm install dotenv
Your packages.json file should look similar to this:
{ "name": "node.js-dotenv", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "dotenv": "^10.0.0" } }
Note that the version of the dependencies might change in the future.
Project Structure
Our project is going to be simple. We just want to see how we can use dotenv. All we need to do is to create an “app.js” and the “.env” file.
π node_modules π app.js - create this file .env - create this file π package-lock.json π package-json
Usage
We need to require dotenv as early as possible in our application in order to be able to access the environment variables that we will create shortly.
In “app.js” file require dotenv by adding the following line of code:
require('dotenv').config()
You can also set a specific path to your .env file if you wish
require('dotenv').config({ path: '/custom/path/to/.env' })
Another thing that you can do is to change the default “utf8” encoding:
require('dotenv').config({ encoding: 'latin1' })
Now we need to create our .env file which will store our variables. Create the file and let’s add a few demo variables that we can display.
MESSAGE=HELLO WORLD
In the example above “MESSAGE” is our variable name and “HELLO WORLD” is our string – value. Let’s display the value in our “app.js” file by console logging it.
Back to our “app.js” file we can bring the environment variable by using “process.env” and then the variable name:
require('dotenv').config(); // Display Hello World console.log(process.env.MESSAGE);
To run this, open your console and run “app.js” with node by doing the following:
node app.js
This should run our application and console log the message and that’s pretty much it! Fairly simple, yet super useful.
Remember not to upload your keys, passwords and so on in places like Github. Use gitignore to prevent that from happening.
Real Life Example – Simple HTTP Server
Let’s say that we wanted to create a very simple HTTP Server using Node.js. You could use the “.env” file to store the hostname and the port name like in the example below:
HOSTNAME=127.0.0.1 PORT=3000
In the example below, we will pull the “HOSTNAME” and the PORT:
const http = require('http'); require('dotenv').config(); const hostname = process.env.HOSTNAME; const port = process.env.PORT; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Now run the application:
node app.js
If everything went well, you should get a message in your console saying “Server running at http://127.0.0.1:3000”. This means that you successfully pulled out the environment variables and created a very simple HTTP Server.
If you open the address in your browser “http://127.0.0.1:3000” you should get “Hello World”.
This was a very simple example of how you might use dotenv. I hope that you enjoyed this simple article. Thank you for your time and if you have any questions please comment below.
Tips are never expected, but deeply appreciated if you are able. It helps me create more content like this.
Thank you for reading this article. Please consider subscribing to my YouTube Channel.
Credit:
- https://www.npmjs.com/package/dotenv
- Photo by SCREEN POST on Unsplash
More Resources: