Practical Introduction to Environment Variables Using Node.js
Tags: beginners, node, dotenv
Published: 2024-07-05 07:55:30

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cjan9yacrxscrlv2c7gi.png)

## 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](https://en.wikipedia.org/wiki/Environment_variable#Examples).

**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):
```bash
PORT=3000 PRODUCT_API=https://product-api.com/ node index.js
```

**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](https://www.npmjs.com/package/dotenv) 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](https://github.com/GyulizH/enviroment-variables-demo) that demonstrates the use of environment variables and how they can change the behavior of our program.

```js
//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}`);
});
```

We pass variables via key value pairs before executing our program:
```bash
WHO=COMMAND_PROMPT PORT=3000 ENV=PRODUCTION node index.ts
```
### Passing variables using dotenv
Contents of .env file: 
```js
PORT=3000
WHO=DOT_ENV
ENV=PRODUCTION
```

```js
//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}`);
});
```

To execute our program:
```bash
node index-dotenv.ts
```
## Conclusion
This was a brief introduction to environment variables. For more details and best practices, refer to the following resources:

- [The Twelve-Factor App section on enviroment variables](https://12factor.net/config) 
- [Environment variables best practices](https://dev.to/khalidk799/environment-variables-its-best-practices-1o1o) 
- [remix.run documentation](https://remix.run/docs/en/main/guides/envvars)