Practical Introduction to Environment Variables Using Node.js

gyulizh

GyulizH

Posted on July 5, 2024

Practical Introduction to Environment Variables Using Node.js
  • What are they?
  • Why would I need to use them?
  • How to define them
  • Example Repo

What are environment variables?

Environment variables are key-value pairs that can be injected into a program dynamically during runtime.
The list of variables come from the shell (e.g., Z shell) that executes our program (1) and is extended during the execution of our program.
The final list of environment variables our program reads comes from a few places:

  • our system currently active user(1)
  • shell session (2)
  • key-value pair we pass to our program (3) Image description

Why would we need environment variables?

The simplest scenario is enabling our program to function in various contexts (development, staging, production) without needing to modify the code.
Another use case would involve setting the URLs of third-party services that our program depends on.

How to define environment variables

side note: system environment variables
Every system where our program is running comes with default set of variables.
They differ from system to system and there is not a single answer, but the most common are: PATH, SHELL, HOME, wikipedia article on the subject.

Defining environment variables via command prompt

We can define them via simple key-value pair before executing our program, in this example we have defined 2 variables that our program depends on(Port and productApi):

PORT=3000 PRODUCT_API=https://product-api.com/ node index.js
Enter fullscreen mode Exit fullscreen mode

Defining the via package, dotenv for Node.js
Our programs may require dozens of variables, and using the command line to pass them could become cumbersome. For this purpose, the industry practice is to use the dotenv package that help us define environment variables in a .env file within the folder of our program and dotenv will make those key-value pairs available to our program as if they had been defined via the command line prompt.

Example Repository

Passing environment variables via command line prompt

Here is a repository that demonstrates the use of environment variables and how they can change the behavior of our program.

//index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 9000;
const who = process.env.WHO;

app.get("/", (req, res) => {
  res.send(`Hello ${who}!`);
});

app.listen(port, () => {
  console.log(`${who}: Example app listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

We pass variables via key value pairs before executing our program:

WHO=COMMAND_PROMPT PORT=3000 ENV=PRODUCTION node index.ts
Enter fullscreen mode Exit fullscreen mode

Passing variables using dotenv

Contents of .env file:

PORT=3000
WHO=DOT_ENV
ENV=PRODUCTION
Enter fullscreen mode Exit fullscreen mode
//index-dotenv.js
const express = require("express");
//make sure dotenv is initialised as soon as possible in our program
require("dotenv/config");

const app = express();
const port = process.env.PORT || 9000;
const who = process.env.WHO;

app.get("/", (req, res) => {
  res.send(`Hello ${who}!`);
});

app.listen(port, () => {
  console.log(`${who}: Example app listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

To execute our program:

node index-dotenv.ts
Enter fullscreen mode Exit fullscreen mode

Conclusion

This was a brief introduction to environment variables. For more details and best practices, refer to the following resources:

💖 💪 🙅 🚩
gyulizh
GyulizH

Posted on July 5, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related