Type-safe environment variable validation function that loads and validates environment variables based on a schema
The validateEnv function is the core utility of env-core that validates and loads environment variables based on a provided schema. It ensures type safety and provides detailed error messages when validation fails.
An object describing the expected environment variables and their types. Each key in the schema represents an environment variable name, and the value can be:
A constructor (String, Number, or Boolean) for required variables
An object with type, required, and default properties for advanced configuration
A configuration object containing environment variables. This parameter is used for NestJS integration with the @nestjs/config module. When provided, the function validates this object instead of loading from a file.
The name of the environment file to load. If not provided, defaults to .env in the current working directory. This parameter is ignored when config is provided.
Returns an object containing the validated environment variables with proper TypeScript types inferred from the schema. The return type is fully type-safe and provides autocomplete for all defined environment variables.
Show Type inference
The return type automatically infers the correct TypeScript type for each variable:
String → string
Number → number
Boolean → boolean
Schema items with defaults → inferred from default value type
import { validateEnv } from 'env-core';const env = validateEnv({ PORT: Number, NODE_ENV: String, DEBUG: Boolean,});// env.PORT is typed as number// env.NODE_ENV is typed as string// env.DEBUG is typed as booleanconsole.log(`Server running on port ${env.PORT}`);