@wuyuchentr/env-validator
v1.0.0
Published
Validate .env variables against expected types and patterns at startup.
Maintainers
Readme
@wuyuchentr/env-validator
Validate .env variables against expected types, patterns, and choices at startup. Fail fast when configuration is wrong.
Install
npm install -g @wuyuchentr/env-validatorQuick start
Create env-validator.config.js in your project root:
module.exports = {
NODE_ENV: { type: 'string', pattern: /^(dev|staging|prod)$/, required: true },
PORT: { type: 'port', required: true },
DATABASE_URL: { type: 'url', required: true },
DEBUG: { type: 'boolean', default: 'false' },
LOG_LEVEL: { type: 'string', choices: ['debug', 'info', 'warn', 'error'], default: 'info' },
};Run:
npx @wuyuchentr/env-validatorSchema options
| Option | Type | Description |
|-----------|------------|-------------|
| type | string | One of: string, number, boolean, email, url, port |
| required | boolean | Whether the variable is required (default true) |
| default | any | Fallback value when not set (implies required: false) |
| pattern | RegExp | Custom regex pattern to match against |
| choices | string[] | List of allowed values |
| message | string | Custom error message |
Usage as library
const { validate } = require('@wuyuchentr/env-validator');
const { errors, env } = validate(process.env, {
PORT: { type: 'port', required: true },
});
if (errors.length) {
console.error('Invalid config:', errors);
process.exit(1);
}
console.log('Parsed PORT:', env.PORT); // number