DEV Community

Wallace Freitas
Wallace Freitas

Posted on

How to validate environment variables in Node.js?

Hey devs 👋🏻

In this article I will teach an alternative to validate the content of environment variables using the package env-var to Node.js.

Requirements

✓ NodeJS v20.6 or later
✓ Knowledge in pnpm package (or any manager package)
✓ Basic Knowledge in Javascript/TypeScript
✓ Knowledge in tsnd package (if use TS)

env-var

This is a package that is responsible for verifying, validating and sanitizing environment-variables used in projects in Node.js or web applications.

Getting started

Firstly, it is necessary to install the env-var using any package manager (in this case I will use pnpm):

pnpm install env-var
Enter fullscreen mode Exit fullscreen mode

After installation, we will create a simple application to demonstrate the functionality of the package (you can use env-var in both JS and TS:

Let's create a env file:

MONGODB_URL=127.0.0.1
MONGODB_PORT=1400
Enter fullscreen mode Exit fullscreen mode

Then, we will create an application:

import env from 'env-var'

function testeWithEnvVar() {
  const mongodbURL = env.get('MONGODB_URL');
  const mongodbPORT = env.get('MONGODB_PORT');
  console.log(`${mongodbURL}:${mongodbPORT}`)
}

testeWithEnvVar()
Enter fullscreen mode Exit fullscreen mode

Now, run the code below:

npx tsnd --env-file path/to/.env path/to/main.ts

Example:
npx tsnd --env-file .env ./src/main.ts
Enter fullscreen mode Exit fullscreen mode

This will show the following message in the console:

127.0.0.1:1400
Enter fullscreen mode Exit fullscreen mode

But, imagine that we need to validate the content of a URL, validate if it is a valid URL or is not empty, how we can do this?

import env from 'env-var'

function testeWithEnvVar() {
  const mongodbURL = env.get('MONGODB_URL').required().asUrlString();
  const mongodbPORT = env.get('MONGODB_PORT');
  console.log(`${mongodbURL}:${mongodbPORT}`)
}

testeWithEnvVar()
Enter fullscreen mode Exit fullscreen mode

See that we need to add only two chained functions (required and asUrlString). Now, if the environment variable MONGODB_URL is inconsistent, for example, without content or if it is an invalid url, the message on the console will be:

[INFO] 15:58:29 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.2, typescript ver. 5.4.5)
EnvVarError: env-var: "MONGODB_URL" is a required variable, but its value was empty
    at raiseError
.
.
.
[ERROR] 15:58:29 EnvVarError: env-var: "MONGODB_URL" is a required variable, but its value was empty
Enter fullscreen mode Exit fullscreen mode

The idea of the article is not deepened in the use of env-var lib, but yes, to show the possibilities that it offers.

That's all folks...

References

This article was created based on Marcos Schead's post and uses this env-var documentation

Top comments (0)