getEnvx Usage
Parse and validate a .envx file into a fully typed configuration object.
getEnvx()
The getEnvx()
function reads a .envx
file, validates its contents using a defined schema, and returns a fully typed, validated configuration object.
It is designed for environments where you need strict validation and reliable runtime behavior without relying on any global state.
✅ Use Cases
- Typed access to your environment configuration
- Works seamlessly in Node.js, Edge runtimes, or serverless functions
- Ideal for frontend, SSR, or unit-test environments where you want controlled, isolated configs
How It Works
- Loads the specified
.envx
file - Parses and validates each variable using inline or provided schema
- Returns a plain object with strict typing support
You can generate types automatically for full IntelliSense using the CLI.
Example
// types/envx.ts – generated with: npx typenvx types
export interface EnvVars {
API_URL: string;
PORT: number;
}
// usage.ts
import { getEnvx } from "typenvx";
import type { EnvVars } from "./types/envx";
const env = getEnvx<EnvVars>();
console.log(env.API_URL); // ✅ typed as string
console.log(env.PORT); // ✅ typed as number
CLI Type Generation
Use the following to generate your type definitions automatically:
npx typenvx types --typesOutput types/envx.ts
You can now import and use the EnvVars
type to gain type safety across your codebase.
Signature
function getEnvx<T = Record<string, unknown>>(
filePath?: string,
schema?: EnvxSchema
): T
Parameter | Description |
---|---|
filePath | Optional. Custom path to the .envx file (default: ./.envx ) |
schema | Optional. If provided, overrides the inline schema |
Using an Inline Schema
You can embed the schema inside your .envx
file.
Alternatively, pass a separate schema manually:
import { getEnvx } from "typenvx";
import type { EnvxSchema } from "typenvx/schema";
const schema: EnvxSchema = {
API_URL: { type: "string" },
PORT: { type: "number" },
};
const env = getEnvx("./config/app.envx", schema);
Validation Behavior
-
Validates all variables against the schema (type + required checks)
-
Throws an error if:
- File is missing
- Type mismatch occurs
- Required variable is not defined
Use try/catch to gracefully handle runtime errors.
Related APIs
Function | Description |
---|---|
loadEnvx() | Parses .envx and returns the object while injecting it globally |
getEnv() | Parses pre-compiled .env using the envx.meta.json schema |