🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

envalid

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
e

envalid

Validation for your environment variables

8.0.0
latest
100

Supply Chain Security

100

Vulnerability

100

Quality

83

Maintenance

100

License

Version published
Weekly downloads
326K
-12.35%
Maintainers
1
Weekly downloads
 
Created
Issues
7

What is envalid?

The envalid npm package is a library for validating and accessing environment variables in Node.js applications. It helps ensure that your environment variables are present and correctly formatted, reducing the risk of runtime errors due to misconfiguration.

What are envalid's main functionalities?

Environment Variable Validation

This feature allows you to define and validate environment variables with specific types and constraints. The `cleanEnv` function ensures that the environment variables are present and correctly formatted, providing default values if necessary.

const envalid = require('envalid');
const { str, num, bool } = envalid;

const env = envalid.cleanEnv(process.env, {
  NODE_ENV: str({ choices: ['development', 'production', 'test'] }),
  PORT: num({ default: 3000 }),
  DEBUG: bool({ default: false })
});

console.log(env.NODE_ENV); // 'development', 'production', or 'test'
console.log(env.PORT); // 3000 if not specified
console.log(env.DEBUG); // false if not specified

Custom Validators

Envalid allows you to create custom validators for environment variables using the `makeValidator` function. This is useful for more complex validation logic that isn't covered by the built-in validators.

const envalid = require('envalid');
const { makeValidator } = envalid;

const myCustomValidator = makeValidator(x => {
  if (x !== 'foo' && x !== 'bar') throw new Error('Must be either foo or bar');
  return x;
});

const env = envalid.cleanEnv(process.env, {
  MY_VAR: myCustomValidator()
});

console.log(env.MY_VAR); // 'foo' or 'bar'

Type Coercion

Envalid automatically coerces environment variables to the specified types. This ensures that your application receives the correct data types, reducing the need for manual type conversion.

const envalid = require('envalid');
const { str, num, bool } = envalid;

const env = envalid.cleanEnv(process.env, {
  MY_STRING: str(),
  MY_NUMBER: num(),
  MY_BOOLEAN: bool()
});

console.log(typeof env.MY_STRING); // 'string'
console.log(typeof env.MY_NUMBER); // 'number'
console.log(typeof env.MY_BOOLEAN); // 'boolean'

Other packages similar to envalid

FAQs

Package last updated on 20 Sep 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts