Getting Started with dotenvx
dotenvx is a powerful, type-safe environment configuration format that extends the traditional .env files with validation and dynamic features.
Installation
Install dotenvx using your preferred package manager.
npm install dotenvxjsBasic Usage
Here's how to get started with dotenvx in your Node.js application.
1Create a .envx file
Create a .envx file in your project root with schema definitions:
1# .envx - Modern environment configuration with schema
2DEV_MODE=false
3
4# Smart interpolation with ternary expressions
5API_URL=${DEV_MODE} ? "http://localhost:3000" : "https://api.example.com"
6API_TOKEN=${DEV_MODE} ? "dev-token" : "prod-token"
7FULL_API_URL="${API_URL}?token=${API_TOKEN}&env=${NODE_ENV}"
8
9# Basic configuration
10PORT=8080
11DATABASE_NAME="myapp_db"
12
13# Multiline strings with triple quotes
14DATABASE_CONFIG="""
15{
16 "host": "localhost",
17 "port": 5432,
18 "ssl": true,
19 "pool": {
20 "min": 2,
21 "max": 10
22 }
23}
24"""
25
26# Schema definitions (always at the bottom)
27[DEV_MODE]
28type="boolean"
29description="Development mode flag"
30default=false
31
32[API_URL]
33type="url"
34required=true
35description="Main API endpoint URL"
36
37[PORT]
38type="number"
39required=true
40description="Server port number"
41default=3000
42
43[NODE_ENV]
44type="enum"
45values=["development", "production", "test", "staging"]
46default="development"
47required=true
48description="Application environment"2Load in your application
Import and use dotenvx in your Node.js application for type-safe environment variable access:
1import { loadEnvx, getEnvx, getEnv } from 'dotenvxjs';
2import { Envx } from './envx.ts';
3
4// Load and validate environment variables from .envx into process.env
5loadEnvx();
6
7// ✅ getEnvx(): Use when you want to read and validate from .envx directly at runtime.
8// You can use it during development or in production **if you include .envx** in your server.
9// Warning: not all platforms (e.g. Vercel, Docker) support .envx natively.
10const envxEnv = getEnvx<Envx>();
11console.log(envxEnv.PORT); // Type: number
12console.log(envxEnv.DEV_MODE); // Type: boolean
13
14// ✅ getEnv(): Recommended for production use.
15// Reads from standard .env files, but still provides full type safety using the
16// precompiled `.envx.meta.json` file generated during build.
17const env = getEnv();
18console.log(env.API_URL); // Inferred as string
19console.log(env.PORT + 1000); // Inferred as number
20
21/*
22🏁 Which one should you use?
23
24- getEnvx():
25 - Reads directly from .envx at runtime
26 - Performs full validation and supports advanced features like interpolation and schema-based types
27 - Only use in production **if you deploy .envx to your server**
28
29- getEnv():
30 - Reads from .env only
31 - No runtime validation (faster, safer for production)
32 - Requires a valid `.envx.meta.json` file generated via `npx dotenvxjs types`
33 - Ideal for production: works seamlessly with Docker, CI/CD, Vercel, etc.
34*/
35
361import { getEnv } from "dotenvxjs";
2
3// Loads and validates using .envx.meta.json at runtime
4const env = getEnv();
5
6console.log(env.PORT);- No more type casting (parseInt, === 'true', etc.)
- Validation errors at startup instead of runtime crashes
- TypeScript integration for autocomplete and type checking
- Default values for optional variables
.envx File Syntax
Learn the syntax and features of .envx files that go beyond traditional .env files.
1# Basic variable assignment
2KEY="value"
3NUMBER=123
4BOOLEAN=true
5
6# Comments start with #
7# This is a comment
8
9# Multiline strings with triple quotes
10MULTILINE="""
11This is a
12multiline string
13with "quotes" inside
14"""
15
16# Variable interpolation
17BASE_URL="https://api.example.com"
18API_URL="${BASE_URL}/v1"
19
20# Ternary expressions
21IS_DEV=true
22API_KEY=${IS_DEV} ? "dev-key" : "prod-key"
23
24# Schema definitions
25[KEY]
26type="string"
27required=true
28description="API key for authentication"
29
30[NUMBER]
31type="number"
32min=0
33max=1000
34description="Maximum number of items"
35
36[BOOLEAN]
37type="boolean"
38default=false
39description="Feature flag"
40
41[ENUM_VALUE]
42type="enum"
43values=["option1", "option2", "option3"]
44default="option1"
45description="Selected option"Schema & Validation
Define schemas for your environment variables to ensure type safety and validation.
1# Schema definition syntax
2[VARIABLE_NAME]
3type="string|number|boolean|enum|url|email"
4description="Human readable description"
5required=true|false
6default="default value"
7
8# Additional type-specific validations
9# For enum:
10values=["option1", "option2", "option3"]
11
12# vsCode plugin specific
13depracted=true # if true, a warning is specified in the variable vsCode plugin must be installed
14description="...." # thanks to the variable schema with the description, a description is added to the variable with vscode, so that it can be known what the variable is without looking at the schema again with hover
15
16# Example schema definitions
17[API_KEY]
18type="string"
19required=true
20description="API key for authentication"
21
22[MAX_CONNECTIONS]
23type="number"
24default=10
25description="Maximum number of concurrent connections"
26
27[DEBUG_MODE]
28type="boolean"
29default=false
30description="Enable debug logging"
31
32[LOG_LEVEL]
33type="enum"
34values=["debug", "info", "warn", "error"]
35default="info"
36description="Application log level".envx.meta.json file is a machine-readable output that contains schema definitions, default values, and metadata compiled from your .envx file. It's primarily used by the getEnv() function during runtime to ensure proper typing and validation.Variable Interpolation
Use variable interpolation and ternary expressions for dynamic configuration.
1# Basic variable interpolation
2BASE_URL="https://api.example.com"
3API_URL="${BASE_URL}/v1"
4FULL_URL="${API_URL}/resource?token=abc123"
5
6# Nested interpolation
7PREFIX="api"
8SUFFIX="v1"
9NESTED_URL="https://${PREFIX}.example.com/${SUFFIX}"
10
11# Ternary expressions
12IS_DEV=true
13API_KEY=${IS_DEV} ? "dev-key-12345" : "prod-key-67890"
14LOG_LEVEL=${IS_DEV} ? "debug" : "info"
15
16# Combining ternary and interpolation
17ENV="development"
18BASE=${ENV} == "development" ? "http://localhost:3000" : "https://api.example.com"
19AUTH_URL="${BASE}/auth"
20USER_URL="${BASE}/users"
21Production Usage
Use getEnv() for fast, safe, type-aware environment access in production.
1// 🏭 Production-ready, schema-aware environment access
2
3// In production environments, it is often safer and more performant to use
4// traditional `.env` files instead of `.envx` files.
5// The `getEnv()` function reads environment variables from `.env` files,
6// not `.envx`, but still provides strong type safety by leveraging
7// the precompiled `.envx.meta.json` schema generated at build time.
8
9import { getEnv } from 'dotenvxjs';
10
11const env = getEnv();
12
13console.log(env.API_URL); // TypeScript infers this as string
14console.log(env.PORT + 1000); // TypeScript infers this as number
15console.log(env.DEV_MODE); // TypeScript infers this as boolean
16
17// ✅ Why use getEnv() in production?
18
19// - Reads variables only from `.env` files, avoiding `.envx` parsing at runtime.
20// - No runtime schema parsing or validation, improving startup performance.
21// - TypeScript types are inferred from the precompiled `.envx.meta.json` file,
22// ensuring type safety without runtime overhead.
23// - Fully compatible with production deployment environments such as Docker,
24// CI/CD pipelines, and serverless platforms where runtime validation is undesirable.
25
26// 🔧 Usage recommendations:
27// - Use `getEnvx()` during development or if you need runtime validation and you
28// deploy `.envx` files on the server.
29// - Use `getEnv()` in production to maximize performance, security, and compatibility.
30
31TypeScript Integration
Generate TypeScript types from your schema for complete type safety.
1// 1. Generate TypeScript types from your schema
2// Run: npx dotenvxjs types --output env.ts
3
4// 2. The generated envx.ts file will look like:
5interface Envx {
6 PORT: number;
7 API_URL: string;
8 DEV_MODE: boolean;
9 NODE_ENV: 'development' | 'production' | 'test' | 'staging';
10 // ... other variables from your schema
11}
12
13// 3. Usage in your TypeScript code
14import { loadEnvx, getEnvx, getEnv } from 'dotenvxjs';
15import { Envx } from './envx.ts';
16
17// Load and validate environment variables from .envx into process.env
18loadEnvx();
19
20// ✅ getEnvx():
21// Reads directly from .envx with full schema validation at runtime
22// Suitable for development or production ONLY IF you deploy .envx files
23const envxEnv = getEnvx<Envx>();
24const nodeEnvx: 'development' | 'production' | 'test' | 'staging' = envxEnv.NODE_ENV;
25
26// ✅ getEnv():
27// Reads from .env files, no runtime validation
28// Type safety is inferred from the precompiled `.envx.meta.json`
29// Recommended for production for better performance and compatibility
30const env = getEnv();
31const nodeEnv: 'development' | 'production' | 'test' | 'staging' = env.NODE_ENV;
32
33/*
34🏁 Which method to use?
35
36- getEnvx():
37 - Runtime reads from .envx with full validation
38 - Use if .envx files are present on the server
39
40- getEnv():
41 - Reads from .env only, no runtime validation
42 - Requires `.envx.meta.json` generated at build time
43 - Ideal for production environments (Docker, CI/CD, Vercel, etc.)
44*/
45
46Examples
Real-world examples of using .envx files and dotenvx in different frameworks.
1// Next.js example
2// In your .envx file
3NEXT_PUBLIC_API_URL="https://api.example.com"
4NEXT_PUBLIC_FEATURE_FLAGS="""
5{
6 "newUI": true,
7 "betaFeatures": false
8}
9"""
10DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
11
12[NEXT_PUBLIC_API_URL]
13type="url"
14required=true
15
16[NEXT_PUBLIC_FEATURE_FLAGS]
17type="json"
18required=true
19
20[DATABASE_URL]
21type="string"
22required=true
23
24// In your next.config.js
25const { loadEnvx } = require('dotenvxjs');
26// if you use process.env
27loadEnvx();
28
29
30// lib/env.ts
31// In your app
32import { getEnvx } from 'dotenvxjs';
33export const env = getEnvx();
34
35// Server-side
36import {env} from "/lib/env.ts";
37
38export async function getServerSideProps() {
39 const dbUrl = env.DATABASE_URL;
40 // Connect to database using dbUrl
41 return { props: { /* ... */ } };
42}
43
44// Client-side (only NEXT_PUBLIC_ variables)
45export default function HomePage() {
46 const apiUrl = env.NEXT_PUBLIC_API_URL;
47 const featureFlags = JSON.parse(env.NEXT_PUBLIC_FEATURE_FLAGS);
48
49 return (
50 <div>
51 <h1>API URL: {apiUrl}</h1>
52 {featureFlags.newUI && <NewUIComponent />}
53 </div>
54 );
55}CLI Commands
dotenvx provides a comprehensive CLI for validating, building, and managing your environment configurations.
Usage:
npx dotenvxjs buildOptions:
| Option | Description | Default |
|---|---|---|
| -i, --input <file> | Path to the input .envx file | .envx |
| -o, --output <file> | Path to the generated .env file | .env |
| -m, --metaFilePath <file> | Path to output the .envx.meta.json file | envx.ts |
| --overwrite | Force overwrite of existing output files | false |
Usage:
npx dotenvxjs generateOptions:
| Option | Description | Default |
|---|---|---|
| -i, --input <file> | Path to the input .envx file | .envx |
| -o, --output <file> | Path to the generated .env file | .env |
| -t, --typesOutput <file> | Path to the generated TypeScript definition file | envx.ts |
| -m, --metaFilePath <path> | Directory where .envx.meta.json will be saved | . |
| --overwrite | Force overwrite of existing output files | false |
Usage:
npx dotenvxjs watchOptions:
| Option | Description | Default |
|---|---|---|
| -i, --input <file> | Path to the input .envx file | .envx |
| -o, --output <file> | Path to the generated .env file | .env |
| -t, --typesOutput <file> | Path to the generated TypeScript definition file | envx.ts |
| -m, --metaFilePath <path> | Directory where .envx.meta.json will be saved | . |
| --no-types | Skip TypeScript type generation | false |
| --no-build | Skip .env file generation | false |
| --silent | Suppress CLI output | false |
Usage:
npx dotenvxjs checkUsage:
npx dotenvxjs typesOptions:
| Option | Description | Default |
|---|---|---|
| -i, --input <file> | Path to the input .envx file | .envx |
| -o, --output <file> | Path to the generated TypeScript file | envx.ts |
| -m, --metaFilePath <file> | Path to output the .envx.meta.json file | envx.ts |
Configuration File
envx.config.js is a file that can be used to add pre-cli settings for dotenvx
module.exports = {
input: "./.envx", // Path to your .envx file
output: {
env: "./.env", // Path for generated .env file
types: "./envx.ts", // Path for generated TypeScript definitions
metaFilePath: "./example/", // Folder path for .envx.meta.json
},
overwrite: true, // Overwrite output files if they already exist
};npx dotenvx build # Generates .env from your .envx file
npx dotenvx check # Validates .envx against its schema
npx dotenvx types # Generates TypeScript definitions
npx dotenvx generate # Generates .env, types, and metadata together
npx dotenvx watch # Watches for changes and regenerates outputs automaticallynpx dotenvx build --input ./custom/.envx --output ./custom/.envnpx dotenvx watchimport { getEnv } from "dotenvx";
const env = getEnv();
console.log(env.API_URL);