new-env-validator-guard
v1.0.0
Published
A lightweight, dependency-free environment variables validator for Node.js applications.
Maintainers
Readme
env-validator-guard
A lightweight, zero-dependency environment variables validator for Node.js applications. Ensures your environment variables are set, typed correctly, and match validation rules before your application starts up.
Installation
npm install new-env-validator-guardFeatures
- 🚀 Zero dependencies — extremely fast and lightweight.
- 🛠️ Type coercion — converts string inputs to actual
number,integer, orbooleantypes. - 🎯 Defaults — provides fallback values for optional env variables.
- 🔍 Flexible Rules — supports required fields, value constraints (
enum), regex matching (pattern), and custom validate functions. - ⚙️ Configurable Actions — throw exceptions (
throw), warn on console (warn), or just return validation errors (return).
Usage
const { validateEnv } = require('env-validator-guard');
// Define validation schema
const schema = {
PORT: { type: 'number', default: 3000, required: true },
NODE_ENV: { type: 'string', enum: ['development', 'production', 'test'], default: 'development' },
DATABASE_URL: { type: 'string', required: true },
API_TIMEOUT: { type: 'integer', default: 5000 },
ENABLE_FEATURE: { type: 'boolean', default: false },
API_KEY: { type: 'string', pattern: /^[a-zA-Z0-9]{32}$/ } // 32-char alphanumeric
};
try {
// Validates process.env against the schema and casts variables
const { config } = validateEnv(schema);
console.log('Environment is valid!');
console.log('Port:', config.PORT); // 3000 (number)
console.log('Feature Enabled:', config.ENABLE_FEATURE); // false (boolean)
} catch (error) {
console.error(error.message);
process.exit(1);
}Schema Rules Options
Each environment variable schema key can have the following configuration properties:
| Option | Type | Description |
|---|---|---|
| required | boolean | If true, throws error if the environment variable is not defined or is an empty string. |
| type | string | Casts the variable to the specified type: 'string', 'number', 'integer', or 'boolean'. |
| default | any | Default value if the variable is not set in the environment. |
| enum | Array | Restricts the variable value to a specific set of values. |
| pattern | RegExp | string | Regex pattern that the value must match. |
| validate | Function | A custom validator function (value) => boolean | string. Return false or an error string if validation fails. |
Validation Options
validateEnv accepts an optional second options parameter:
const result = validateEnv(schema, {
env: process.env, // Custom environment object
onValidationError: 'return' // 'throw' (default), 'warn', or 'return'
});
if (!result.success) {
console.log(result.errors); // Array of string validation errors
}License
MIT
