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 or typenvx types
  • You want to avoid shipping .envx files to production
  • You need type-safe, validated configuration with minimal runtime overhead

How It Works

  1. Reads the compiled .env file
  2. Loads the envx.meta.json schema
  3. Validates and parses the values according to their types
  4. 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 file
  • envx.meta.json — validation schema
  • (optionally) envx.ts — your type definitions

Signature

function getEnv<T = Record<string, unknown>>(
  filePath?: string
): T
ParameterDescription
filePathOptional. 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

FunctionReads FileUses SchemaType-SafeSuitable For
getEnvx().envxInline or manualLocal/dev usage
loadEnvx().envxInline or manualDev/runtime load
getEnv().env + schemaenvx.meta.jsonProduction runtime