Error types
The library can produce three types of validation errors:Missing required field
Occurs when a required environment variable is not set and has no default value.- Variable not defined in
.envfile or environment - Variable defined with simple constructor (
String,Number,Boolean) - Variable defined with
required: true(orrequirednot specified)
Type validation error
Occurs when an environment variable value cannot be converted to the expected type.Unsupported type error
Occurs when a schema defines a type that is not supported by env-core.- Using a type other than
String,Number, orBoolean - Passing an invalid constructor or value
Error handling modes
env-core has two different error handling modes depending on the execution context:Standard mode (Node.js/Express)
Used when callingvalidateEnv(schema) or validateEnv(schema, envFile) without a config object.
Behavior
- Validation errors are logged to
console.error - Process exits with code
1usingprocess.exit(1) - Application startup is prevented
Example output
Example code
NestJS mode
Used when callingvalidateEnv(schema, config) with a config object, typically for NestJS integration.
Behavior
- Validation errors are collected
- An
Erroris thrown with formatted error messages - NestJS handles the error and prevents module initialization
Example error
Example code
Error message format
All validation errors follow a consistent format:- Header:
"Environment validation failed:" - Each error is prefixed with
"- " - Errors are listed in the order they were encountered
- Multiple errors are collected and reported together
Common error scenarios
Scenario 1: Missing .env file
.env file with the required variables:
Scenario 2: Invalid type values
.env file:Scenario 3: Mixed errors
.env file:Best practices
Fail fast on startup
PlacevalidateEnv calls at the very beginning of your application to catch configuration errors before any resources are initialized:
Provide clear variable names
Use descriptive environment variable names to make error messages more helpful:Use defaults for optional configuration
Provide sensible defaults to reduce required environment variables:Document required variables
Maintain a.env.example file with all required variables: