Logo

dev-resources.site

for different kinds of informations.

Practical Introduction to Environment Variables Using Node.js

Published at
7/5/2024
Categories
beginners
node
dotenv
Author
gyulizh
Categories
3 categories in total
beginners
open
node
open
dotenv
open
Author
7 person written this
gyulizh
open
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:

dotenv Article's
30 articles in total
Favicon
Load Environment Variables using dotenv-local
Favicon
Hashicorp Vault Agent Tutorial: Generating .env from Vault Secrets
Favicon
Flutter Web | Build with .env File
Favicon
Learn .env in Express.js for Beginners (Effortless Setup)
Favicon
How to Hide Only API Keys Instead of Entire Files on GitHub and From Its Commit History
Favicon
Practical Introduction to Environment Variables Using Node.js
Favicon
From dotenv to dotenvx: Next Generation Config Management
Favicon
How to use `.env` file v:20.6.0 `dotenv` npm package do not use.
Favicon
Community Spotlight: David Cochrum
Favicon
Node.js 20.6.0 includes built-in support for .env files
Favicon
What is a .env.vault file
Favicon
Environment variables and configuration anti patterns in Node.js applications
Favicon
Dotenv: Python app environment variable vs. Linux environment variable
Favicon
Node.js includes built-in support for .env files
Favicon
How does python-dotenv simplify Configuration Management?
Favicon
Env::Dot
Favicon
How do you set up .env variables in your NextJS project ?
Favicon
Using ENV file in React & Webpack
Favicon
A simple trick for your dotenv files
Favicon
dotenv and typescript
Favicon
Environment variables & Its best practices
Favicon
Password Manage your environment and secrets with bitwarden
Favicon
5 reasons why your .env environment variables don't work
Favicon
Creating a DotEnv Loader in PHP
Favicon
NextJS - Get rid of DotENV
Favicon
Setting-up a Django project for production
Favicon
Stop using Dotenv in your front-end
Favicon
Supercharge your .env powered projects!
Favicon
Ways to load env variables for your script
Favicon
Doppler: The Triumph and Tragedy of .env Files

Featured ones: