Node.js read env var is one of the most typical yet (sometimes) challenging tasks you will do as a Node.js developer.
Running the node
command starts an operating system process. The process
object and its env
attribute present your Node.js application with an interface to read env vars. Besides, you can attach custom env vars to the process.env
object and read them with the help of packages like dotenv
.
# initialize an npm package
npm init -y
# install the Node.js read env var package
npm install dotenv
# use an env var
process.env.[ENVIRONMENT VARIABLE]
As explained in this tutorial, effectively reading environment variables requires an in-depth knowledge of the types and usage of environment variables. Read on to learn more.
How to read env variable in Node.js
An env var, short for an environment variable, is a collection of software, devices, and networks supporting the gathering and exchange of data needed by an application.
Node.js has several built-in APIs and modules to ease communicating with the operating system. One of the modules is the process
object: an interface between the operating system and your node environments. Your code sends instructions to the interface and receives outputs from the operating system through the process
object.
The process
object has attributes to interact with your application. For example, the env
property exposes environment variables to your Node.js code. You can list all the environment variables by entering the REPL mode,
node
and typing process.
followed by double-tapping the tab
key.
You can list the env vars using the terminal and a code editor, as shown below.
List env vars on the terminal
You can view your system's environment variables by running the node command followed by the process.env
attribute.
node
> process.env
# OR use the Node CLI
node -p "process.env"
Alternatively, you can console-log the output. For example, create app.js
file,
# create and open a file with vim.
vim app.js
# OR create a file with the touch command.
touch app.js
# and open the file with Visual Studio Code.
code app.js
write console.log(process.env)
in the file,
save the file, then return to the terminal and run the file with the node
command.
node app.js
The system returns its environment variables.
Now that you understand the roots of env vars and how to list them on the terminal, it would be best to learn their types before seeing how to read them in your Node.js code.
Understand the main types of environment variables
1. System environment variables
Your operating system needs the environment variables to run. For example, the USER environment variable specifies the logged-in user. The HOME environment variable tells the home directory: a directory containing a given user's files.
You can view an operating system's environment variable by attaching its name to process.env
before printing the result.
node -p "process.env.HOME"
Here I am printing the HOME env var using the Node.js CLI's -p
option.
2. Custom environment variables
Like the operating system, your application needs env vars to communicate data between certain software or networks. Here are examples of environment variables you will likely set for your Node.js application.
MongoDB is a document-oriented database program. You can download and connect your Node.js application to the MongoDB client. Alternatively, you can connect to the MongoDB Atlas, a cloud version. The connection is possible through a MongoDB URI env var.
Node.js read env var entails clients and servers. A client is a computer requesting resources from your Node.js server. The server, in turn, determines the resource to send depending on the set authentication and authorization rules. The server listens for requests on the PORT environment variable.
JSON Web Token (JWT) is one of the Node.js authentication strategies. It contains encoded objects that identify clients and servers. The identification is possible through public and private keys often referred to as an AUTH or SECRET environment variable.
3. Built-in environment variables
Apart from the OS and custom environment variables, you can change Node's behavior by setting the built-in environment variables like NODE_DEBUG.
You can list the built-in environment variables by running the node command with the -h
option.
node -h
Node.js read env vars using the dotenv package
Assume you want to Node.js read env vars that change when you switch between the development and production environment variables like the PORT environment.
It is recommended to store the (often) sensitive data in a .env
file and read the file using the process.env
object and the dotenv
package. Here are the steps to Node.js read env vars in your applications.
Initialize an npm
package.
npm init -y
Install the dotenv
package.
npm i dotenv
Create the entry and .env
files, then store the environment variable in a .env
file.
touch index.js .env
echo "PORT=3000" > .env
Now set the server to listen on the host environment's PORT or 5000 in the entry file.
cat the index.js
file
cat >> index.js
Write the index.js
file's contents
const http = require('http');
const dotenv = require('dotenv');
if (process.env.NODE_ENV !== 'production') dotenv.config() ;
const server = http.createServer((req, res) => {
if (req.url === '/') res.end('Request received')
});
const PORT = process.env.PORT || 5000;
server.listen(PORT, console.log(`server listens on port ${PORT}`));
Lastly, run the entry file to test if our Node.js read env var mission was successful.
node index.js
If the application runs on port 3000 instead of the 5000, we will have succeeded in reading environment variables using the dotenv
package.
And yes, we successfully Node.js read env variables!
Conclusion
The process
module with its env
attribute accomplishes the Node.js read env var process. The en var could be the operating system, built-in, or custom.
For example, you can read a custom environment variable by attaching its name/key to the process.env
. The dotenv
package then loads the environment variable from the .env
file toprocess.env
.