A simple environment variables validator for Node.js and web browsers

Overview

βœ“ valienv

A simple environment variables validator for Node.js and web browsers.

mit licence npm version bundlephobia

Installation

$ npm i valienv --save
# --- or ---
$ yarn add valienv

πŸ“˜ Basic usage

This library exports a main function: validateEnv.
Using validators, you can parse, validate and type required environment variables (other variables will be excluded).

typeof env = Readonly<{ // ACCENT_COLOR: string; // TIMEOUT_MS: number; // ENABLE_ANALYTICS: boolean; // }>">
import { bool, nbr, str, validateEnv } from "valienv";

// with process.env = {
//   ACCENT_COLOR: "#0099e5",
//   TIMEOUT_MS: "5000",
//   ENABLE_ANALYTICS: "true",
// }

export const env = validateEnv({
  env: process.env,
  validators: {
    // we validate env using bundled validators
    ACCENT_COLOR: str,
    TIMEOUT_MS: nbr,
    ENABLE_ANALYTICS: bool,
  },
});

// -> typeof env = Readonly<{
//   ACCENT_COLOR: string;
//   TIMEOUT_MS: number;
//   ENABLE_ANALYTICS: boolean;
// }>

⚠️  In case of incorrect environment variables, the function will throw an EnvValidationError exposing invalidVariables and missingVariables names (not their values) to prevent your application from starting.

πŸ“• Advanced usage

The validateEnv function accepts prefix and overrides options.

prefix

Some bundlers only expose prefixed environment variables to your application (ex: Create React App, Vite).
The prefix option is very useful to remove them.

typeof env = Readonly<{ CONTACT_EMAIL: string }>">
import { str, validateEnv } from "valienv";

// with process.env = {
//   REACT_APP_CONTACT_EMAIL: "[email protected]",
// }

export const env = validateEnv({
  env: process.env,
  prefix: "REACT_APP_",
  validators: {
    CONTACT_EMAIL: str,
  },
});

// -> typeof env = Readonly<{ CONTACT_EMAIL: string }>

overrides

The overrides option is useful to override some variables in some contexts.

typeof env = Readonly<{ CONTACT_EMAIL: string }>">
import { str, validateEnv } from "valienv";

// with process.env = {
//   CONTACT_EMAIL: "[email protected]",
// }

export const env = validateEnv({
  env: process.env,
  validators: {
    CONTACT_EMAIL: str,
  },
  overrides: {
    ...(process.env.NODE_ENV === "test" && {
      CONTACT_EMAIL: "no-mail",
    }),
  },
});

// -> typeof env = Readonly<{ CONTACT_EMAIL: string }>

⚠️  The values set has to be correctly typed but are not validated.

πŸ”§ Custom validators

By default, valienv only exports 3 validators: str (for string), nbr (for number) and bool (for boolean).
But it's very easy to write your own:

= (value /*: string*/) => { const parsed = parseInt(value); if (parsed > 0 && parsed < 65536) { return parsed; } }; // with process.env = { // PORT: "3000", // } export const env = validateEnv({ env: process.env, validators: { PORT: port, }, }); // -> typeof env = Readonly<{ PORT: number }>">
import { validateEnv, Validator } from "valienv";

// A validator take raw input, try to parse it and
// returns the result in case of valid value:
const port: Validator<number> = (value /*: string*/) => {
  const parsed = parseInt(value);

  if (parsed > 0 && parsed < 65536) {
    return parsed;
  }
};

// with process.env = {
//   PORT: "3000",
// }

export const env = validateEnv({
  env: process.env,
  validators: {
    PORT: port,
  },
});

// -> typeof env = Readonly<{ PORT: number }>

You can even go wild by using stricter types, complex parsing, your favorite validation library, etc! πŸ”₯

{ if (validator.isEthereumAddress(value)) { return value; } }, NODE_ENV: (value) => { if ( value === "development" || value === "test" || value === "production" ) { return value; } }, OPENED_COUNTRIES: (value) => { const array = value.split(","); if (array.every(validator.isISO31661Alpha2)) { return array; } }, }, }); // -> typeof env = Readonly<{ // ETHEREUM_ADDRESS: string; // NODE_ENV: "development" | "production" | "test"; // OPENED_COUNTRIES: string[]; // }>">
import validator from "validator";
import { validateEnv } from "valienv";

// with process.env = {
//   ETHEREUM_ADDRESS: "0xb794f5ea0ba39494ce839613fffba74279579268",
//   NODE_ENV: "development",
//   OPENED_COUNTRIES: "FR,BE,DE",
// }

export const env = validateEnv({
  env: process.env,
  validators: {
    // inlined validators return types are correctly infered
    ETHEREUM_ADDRESS: (value) => {
      if (validator.isEthereumAddress(value)) {
        return value;
      }
    },
    NODE_ENV: (value) => {
      if (
        value === "development" ||
        value === "test" ||
        value === "production"
      ) {
        return value;
      }
    },
    OPENED_COUNTRIES: (value) => {
      const array = value.split(",");

      if (array.every(validator.isISO31661Alpha2)) {
        return array;
      }
    },
  },
});

// -> typeof env = Readonly<{
//   ETHEREUM_ADDRESS: string;
//   NODE_ENV: "development" | "production" | "test";
//   OPENED_COUNTRIES: string[];
// }>

❓ Questions

Why not handling NODE_ENV for us?

Frontend bundlers generally statically replace process.env.NODE_ENV values at build time, allowing minifiers like terser to eliminate dead code from production build. Aliasing NODE_ENV would prevent such optimisations. But if your are working with Node.js, feel free to implement a custom validator for it if you want πŸ™‚ !

You might also like...

Fast, compiled, eval-free data validator/transformer

spectypes Fast, compiled, eval-free data validator/transformer Features really fast, can be even faster than ajv detailed errors, failure will result

Dec 29, 2022

What does the Cosmos Hub validator set looks like without ICF delegations?

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Sep 2, 2022

:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator βœ… Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Dec 14, 2022

Reading emails from Gmail provider using Node.js along with Google API

Reading emails from Gmail provider using Node.js along with Google API

πŸ’» Project summary Reading emails from Gmail provider using Node.js along with Google API (study only). πŸ›  Technologies Project was built using Node.j

Jan 8, 2022

A simple and composable way to validate data in JavaScript (and TypeScript).

A simple and composable way to validate data in JavaScript (and TypeScript).

A simple and composable way to validate data in JavaScript (and TypeScript). Usage β€’ Why? β€’ Principles β€’ Demo β€’ Examples β€’ Documentation Superstruct m

Jan 9, 2023

Simple and basic javascript form validations

JavaScript-Form-Validations Simple and basic javascript form validations Table of Validations: S. No. Type of validation Link 1 Non-empty text field h

Dec 17, 2022

Simple, smart and pleasant validation solution.

nice-validator Simple, smart and pleasant validation solution. Download the latest release or install package via npm or bower $ npm install nice-vali

Nov 18, 2022

Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jan 2, 2023
Comments
  • create oneOf validator

    create oneOf validator

    Hi @zoontek

    I'm currently using valienv on several apps and I've got a suggestion for a new validator named oneOf.
    The goal is making the following validation a little shorter and easier to write:

    export const env = validateEnv({
      env: process.env,
      validators: {
        NODE_ENV: (value) => {
          if (
            value === "development" ||
            value === "test" ||
            value === "production"
          ) {
            return value;
          }
        },
      },
    });
    

    Could be written like this:

    export const env = validateEnv({
      env: process.env,
      validators: {
        NODE_ENV: oneOf(['development', 'test', 'production'] as const),
      },
    });
    

    For now, I haven't written any test or updated the documentation because I prefer to have your opinion on the subject before taking more time on this PR. But if you think this validator is relevant, I can quickly add some tests and update the readme.

    opened by Epimodev 7
  • add details in error message

    add details in error message

    Hi @zoontek!

    I hope everything is going well on your side.

    For a few months I'm using more and more valienv for different projects (front end with Vite or NextJS, node js apps, ...).
    And when someone adds an environment variable, we often forget to put it in our CI for deployments or say to the rest of the team that they have to add an environment variable in their local environment.
    And currently we've got in the terminal just this error message: Some environment variables cannot be validated.

    Even if the problem comes from communication/organisation in my team, I think adding more details in error message could help to understand what's wrong without checking the file defining environment validation.

    So in this PR I added in the error message 2 lines:

    • the first one with invalid variables
    • the second one with missing variables

    What do you think?

    opened by Epimodev 3
  • create nonEmptyString validator

    create nonEmptyString validator

    Summary

    Hello @zoontek

    I hope the end of this year is going well for you.

    I created this PR because I've got a new use case for a project where my env variables can be an empty string. I can give you more details about my use case but I don't think this is really important.

    So I created a new validator nonEmptyString which check if the value isn't an empty string for validation.

    Even if this is easy to create our own validators in our project, I thought it's generic enough and might help other developers using valienv.

    Test Plan

    At the moment I didn't write any tests neither add documentation because I prefer having confirmation from you this PR is relevant before taking time on this. But if you validate this is relevant for valienv, I'll add test and documentation in this PR.

    opened by Epimodev 2
Releases(0.3.0)
Owner
Mathieu Acthernoene
Curious developer.
Mathieu Acthernoene
This is the code repository of the official mun testnet validator node source code.

How to join Munchain network Infrastructure **Recommended configuration:** - Number of CPUs: 4 - Memory: 16GB - OS: Ubuntu 22.04 LTS - Allow all incom

MUN Blockchain 16 Dec 15, 2022
Simple validator for Steuerliche Identifikationsnummer (German personal tax number) according to the official docs (see readme).

simple-de-taxid-validator Important Code of this validator is taken (with small changes like optimization or removing not needed elements) from THIS R

Wojciech 3 Feb 24, 2022
Simple password validator made with Javascript πŸ’›

Password Validator Simple password validator made with Javascript ?? Branch history base-code: a complex logic to password validator. In next branches

Lais FrigΓ©rio 8 Jul 25, 2022
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-06/07/2019-09/2020-12 (draft-04 is supported

Ajv JSON schema validator 12k Jan 4, 2023
ForgJs is a javascript lightweight object validator. Go check the Quick start section and start coding with love

Hey every one im really happy that this repo reached this many stars ?? ,but this repo needs your contibution I started to better document the code th

Hamdaoui Oussama 1.7k Dec 21, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
Tiny Validator for JSON Schema v4

Tiny Validator (for v4 JSON Schema) Use json-schema draft v4 to validate simple values and complex objects using a rich validation vocabulary (example

Geraint 1.2k Dec 21, 2022
A JSONSchema validator that uses code generation to be extremely fast

is-my-json-valid A JSONSchema validator that uses code generation to be extremely fast. It passes the entire JSONSchema v4 test suite except for remot

Mathias Buus 948 Dec 31, 2022
Super Fast Complex Object Validator for Javascript(& Typescript).

Super Fast Object Validator for Javascript(& Typescript). Safen supports the syntax similar to the type script interface. This makes it easy to create

Changwan Jun 31 Nov 25, 2022
Easy HTML Form Validator

Easy HTML Form Validator

Ali Nazari 314 Dec 26, 2022