dotenv-validator
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

dotenv-validator

You can validate environment variables defined in .env with dotenv-validator


Prerequisite

  1. dotenv installed
  2. default value of environment variables is ready
  3. validation rules is ready

Install

npm i dotenv-validator

Usage

If your .env is like below (with invalid host)

HOST=0.0.0.A
PORT=3030

then, validate throw error

import dotenv from 'dotenv'
import validate from 'dotenv-validator'

try {
  const envDefault = {
    HOST: '',
    PORT: '',
  }

  const envRules = {
    HOST: {
      required: true, // default is false
      validator: value => /\d+\.\d+\.\d+\.\d+/.test(value),
    },
  }

  // load .env
  const envParsed = dotenv.config().parsed

  // set default to process.env
  process.env = {...envDefault, ...process.env}

  // validate process.env
  validate({envDefault, envParsed, envRules}) // throw error if process.env is not valid
} catch (e) {
  console.error(e) // print error `'HOST' is not valid in .env`
}

Readme

Keywords

Package Sidebar

Install

npm i dotenv-validator

Weekly Downloads

48

Version

1.0.1

License

MIT

Unpacked Size

12.4 kB

Total Files

7

Last publish

Collaborators

  • keating1729