dotenv-validator
v1.0.1
Published
.env validator
Downloads
80
Readme
dotenv-validator
You can validate environment variables defined in .env
with dotenv-validator
Prerequisite
- dotenv installed
- default value of environment variables is ready
- 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`
}