dotenv-validator

.env validator

Usage no npm install needed!

<script type="module">
  import dotenvValidator from 'https://cdn.skypack.dev/dotenv-validator';
</script>

README

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

and your default-env.js is like below

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

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

then, validate throw error

import {envDefault, envRules} from './default-env'
import dotenv from 'dotenv'
import validate from 'dotenv-validator'

try {
  // 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'`
}