Usage Guide

How to use .envx in your project CLI commands, library usage, examples, and type safety.

.envx Usage Guide

Welcome to the official .envx usage guide. This document explains how to define, validate, and safely consume environment variables across environments using .envx.


⚙️ CLI Usage

You can use the typenv CLI to generate types and compile environment files:

npx typenvx types --typesOutput types/envx.d.ts
npx typenvx generate
  • typenvx types: Generates TypeScript interfaces from your .envx schema.
  • typenvx generate: Compiles .envx into .env and generates envx.meta.json for production usage.

📦 Library API Overview

FunctionReads FromInjects to process.envUse Case
getEnvx().envx❌ NoFrontend / SSR (typed access)
loadEnvx().envx✅ YesBackend / CLI tools
getEnv().env + envx.meta.json❌ NoProduction (compiled access)

✨ Example: Load Typed Variables (Frontend / SSR)

import { getEnvx } from "typenvx";
import type { EnvVars } from "./types/envx";

const env = getEnvx<EnvVars>();
console.log(env.API_URL); // Typed and validated
  • ✅ Reads: .envx
  • ❌ Does not mutate: process.env
  • ✅ Type-safe return

Example: Load and Inject (Backend)

import { loadEnvx } from "typenvx";

loadEnvx(); // injects into process.env
console.log(process.env.API_TOKEN);
  • ✅ Reads: .envx
  • ✅ Injects: process.env
  • ❌ Not typed unless wrapped manually

Example: Production-Safe Load (Compiled)

import { getEnv } from "typenvx";
import type { EnvVars } from "./types/envx";

const env = getEnv<EnvVars>();
console.log(env.PORT);
  • ✅ Reads: .env and envx.meta.json
  • ❌ Does not mutate: process.env
  • ✅ Type-safe and ideal for production

Type Generation

To enable full IntelliSense and compile-time safety, run:

npx typenvx types --typesOutput types/envx.d.ts

This creates a file like:

export interface EnvVars {
  API_URL?: string;
  API_TOKEN?: string;
  PORT: number;
  NODE_ENV: "development" | "production" | "test";
  DEV_MODE?: boolean;
}

✅ Best Practices

  • Use getEnvx() in development, SSR, and frontend apps.
  • Use loadEnvx() in Node.js CLI scripts or backends where global injection is needed.
  • Use getEnv() in production - it consumes the compiled .env + schema and ensures safety without shipping dev files.
  • Always regenerate types after modifying your .envx file.

Common Pitfalls

  • .envx not found → Ensure correct path or use config.input in config file
  • envx.meta.json missing → Run npx typenvx generate before using getEnv()
  • Invalid types → Runtime validation errors show exact variable and type mismatch

Conclusion

.envx gives you the safety of TypeScript with the flexibility of environment variables. Whether you're running on the server, the frontend, or deploying to production use the right tool for the right environment.

If you haven't already, get started by creating a .envx file and running:

npx typenvx types
npx typenvx generate

Happy hacking!