getEnv Usage
Read a compiled .env file and validate it using the generated schema (envx.meta.json).
getEnv()
The getEnv()
function loads a compiled .env
file and validates it against a generated schema from envx.meta.json
, returning a fully typed and verified environment configuration.
It is designed for production or runtime environments where your .envx
files have already been pre-compiled into .env
files with a corresponding schema.
✅ When to Use
- You already ran
typenvx generate
ortypenvx types
- You want to avoid shipping
.envx
files to production - You need type-safe, validated configuration with minimal runtime overhead
How It Works
- Reads the compiled
.env
file - Loads the
envx.meta.json
schema - Validates and parses the values according to their types
- Returns a strictly typed object
It does not mutate any global state and keeps your environment handling deterministic.
Example
// types/envx.ts – generated with: npx typenvx types
export interface EnvVars {
DATABASE_URL: string;
API_KEY?: string;
}
// main.ts
import { getEnv } from "typenvx";
import type { EnvVars } from "./types/envx";
const env = getEnv<EnvVars>();
console.log(env.DATABASE_URL); // string
console.log(env.DEV_MODE); // boolean
CLI Preparation
Before using getEnv()
, you need to generate both the .env
and the envx.meta.json
schema:
npx typenvx generate
This command will output:
.env
— compiled runtime-safe fileenvx.meta.json
— validation schema- (optionally)
envx.ts
— your type definitions
Signature
function getEnv<T = Record<string, unknown>>(
filePath?: string
): T
Parameter | Description |
---|---|
filePath | Optional. Custom path to the .env file (default: .env ) |
The schema path is resolved from envx.config.json
, or defaults to ./envx.meta.json
.
Configuration
You can customize file paths through envx.config.json
:
{
"outputs": {
"env": "./.env",
"types": "./types/envx.ts",
"metaFilePath": "."
},
}
Validation Rules
Validation uses the schema generated during typenvx generate
.
The following checks are enforced:
- Required variables must exist
- Types must match (string, number, boolean, enums, etc.)
- Enum values must be one of the allowed options
On failure, an EnvxError
is thrown with a descriptive message.
Example with Custom Paths
// load from a custom compiled .env + meta file
const env = getEnv<EnvVars>("./.env");
Ensure your envx.config.json
is aligned with the compiled paths.
Comparison
Function | Reads File | Uses Schema | Type-Safe | Suitable For |
---|---|---|---|---|
getEnvx() | .envx | Inline or manual | ✅ | Local/dev usage |
loadEnvx() | .envx | Inline or manual | ✅ | Dev/runtime load |
getEnv() | .env + schema | envx.meta.json | ✅ | Production runtime |
Related
- loadEnvx() — Load and inject
.envx
variables - getEnvx() — Parse raw
.envx
directly