@kitiumai/env-type-generator
v3.0.1
Published
Zero-config TypeScript type generator for .env files with Zod validation, watch mode, and IDE autocomplete support
Maintainers
Keywords
Readme
env-type-generator
Zero-config TypeScript type generator for .env files with Zod validation, watch mode, and IDE autocomplete
Stop writing types for process.env manually. Let env-type-generator do it for you!
Table of Contents
- Features
- Installation
- Quick Start
- Usage
- Examples
- Framework Integration
- CI/CD Integration
- GitHub Actions
- Configuration
- API
- Troubleshooting
- Contributing
- License
Features
- ✅ Zero Config - Works out of the box with sensible defaults
- ✅ Auto-Generation - Generates TypeScript types from existing .env files
- ✅ Type Inference - Optionally infer types (string, number, boolean, object)
- ✅ Runtime Validation - Generate Zod/Yup/Joi schemas for runtime validation
- ✅ Watch Mode - Auto-regenerate on file changes
- ✅ Multiple Files - Support for .env, .env.local, .env.production, etc.
- ✅ Framework Agnostic - Works with any TypeScript project
- ✅ IDE Autocomplete - Get IntelliSense for
process.env
Installation
npm install --save-dev @kitiumai/env-type-generator
# or
yarn add -D @kitiumai/env-type-generator
# or
pnpm add -D @kitiumai/env-type-generatorQuick Start
1. Create your .env file
# Database
DATABASE_URL=postgresql://localhost:5432/mydb
DATABASE_POOL_SIZE=10
# API Keys
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_PUBLISHABLE_KEY=pk_test_xxx
# Features
ENABLE_ANALYTICS=true
MAX_UPLOAD_SIZE_MB=502. Generate types
npx env-type-gen3. Use type-safe environment variables
// TypeScript knows about your env vars!
const dbUrl: string = process.env.DATABASE_URL; // Autocomplete works!
const poolSize: number = env.DATABASE_POOL_SIZE; // Parsed as number
// ❌ TypeScript will catch typos
const invalid = process.env.DATABSE_URL; // Error: Property 'DATABSE_URL' does not existUsage & Tree-Shaking
@kitiumai/env-type-generator is designed with optimal tree-shaking in mind. The package is side-effect free ("sideEffects": false) and provides granular subpath exports for minimal bundle size.
Import Patterns
Import only what you need to minimize bundle size:
// ✅ Granular imports (tree-shakable)
import { GeneratorService } from '@kitiumai/env-type-generator/services/generator-service';
import { EnvParser } from '@kitiumai/env-type-generator/parsers';
import { TypeGenerator } from '@kitiumai/env-type-generator/generators/type-generator';
import { ValidationGenerator } from '@kitiumai/env-type-generator/generators/validation-generator';
import { FileWatcher } from '@kitiumai/env-type-generator/services/file-watcher';
import type { EnvVariable, GeneratorConfig } from '@kitiumai/env-type-generator/types';
import { EnvTypeGeneratorError } from '@kitiumai/env-type-generator/utils/errors';
// ✅ Barrel import (all exports)
import { GeneratorService, EnvParser } from '@kitiumai/env-type-generator';Available Subpath Exports
| Subpath | Exports |
| -------------------------------------------------------------- | ------------------------------- |
| @kitiumai/env-type-generator | All exports (barrel) |
| @kitiumai/env-type-generator/generators | TypeGenerator (alias) |
| @kitiumai/env-type-generator/generators/type-generator | TypeGenerator class |
| @kitiumai/env-type-generator/generators/validation-generator | ValidationGenerator class |
| @kitiumai/env-type-generator/parsers | EnvParser class |
| @kitiumai/env-type-generator/services | GeneratorService (alias) |
| @kitiumai/env-type-generator/services/generator-service | GeneratorService class |
| @kitiumai/env-type-generator/services/file-watcher | FileWatcher class |
| @kitiumai/env-type-generator/types | TypeScript types and interfaces |
| @kitiumai/env-type-generator/utils | Error classes (alias) |
| @kitiumai/env-type-generator/utils/errors | Error classes |
| @kitiumai/env-type-generator/logger | Logger utilities |
Programmatic API
Use the package programmatically in your build scripts:
import { GeneratorService } from '@kitiumai/env-type-generator/services/generator-service';
const generator = new GeneratorService({
envFiles: ['.env', '.env.local'],
outputPath: 'src/types/env.d.ts',
validationLib: 'zod',
validationOutput: 'src/config/env.validator.ts',
parseTypes: true,
strict: true,
});
await generator.generate();Usage
CLI Options
npx env-type-gen [options]| Option | Description | Default |
| -------------------------------- | ---------------------------------------- | ------------------------------- |
| -e, --env-files <files...> | Environment files to parse | .env |
| -o, --output <path> | Output path for type definitions | ./src/types/env.d.ts |
| -v, --validation-lib <library> | Validation library (zod|yup|joi|none) | none |
| -s, --validation-output <path> | Output path for validation schema | ./src/config/env.validator.ts |
| -r, --required <vars...> | Required environment variables | [] |
| -p, --parse-types | Parse and infer types from values | false |
| -t, --strict | Treat all variables as required | false |
| -w, --watch | Watch mode - regenerate on file changes | false |
| -c, --config <path> | Path to config file | - |
Examples
Basic Usage
# Generate types from .env
npx env-type-gen
# Specify custom output path
npx env-type-gen --output ./types/env.d.ts
# Parse multiple env files
npx env-type-gen --env-files .env .env.localWith Type Inference
# Enable type inference (string → number, boolean, etc.)
npx env-type-gen --parse-typesThis will generate:
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL?: string | undefined;
DATABASE_POOL_SIZE?: number | undefined; // ← Inferred as number
ENABLE_ANALYTICS?: boolean | undefined; // ← Inferred as boolean
}
}With Zod Validation
# Generate Zod validation schema
npx env-type-gen --validation-lib zod --parse-typesThis generates env.validator.ts:
import { z } from 'zod';
export const envSchema = z.object({
DATABASE_URL: z.string().optional(),
DATABASE_POOL_SIZE: z
.string()
.transform((val) => Number(val))
.optional(),
ENABLE_ANALYTICS: z
.enum(['true', 'false'])
.transform((val) => val === 'true')
.optional(),
});
export type Env = z.infer<typeof envSchema>;
export const env = envSchema.parse(process.env);With Required Variables
# Mark specific variables as required
npx env-type-gen --required DATABASE_URL STRIPE_SECRET_KEY
# Or mark ALL variables as required (strict mode)
npx env-type-gen --strictWatch Mode
# Auto-regenerate on file changes
npx env-type-gen --watchConfiguration File
Create env-type.config.js:
module.exports = {
envFiles: ['.env', '.env.local'],
outputPath: './src/types/env.d.ts',
validationLib: 'zod',
validationOutput: './src/config/env.validator.ts',
requiredVars: ['DATABASE_URL', 'API_KEY'],
parseTypes: true,
strict: false,
};Then run:
npx env-type-gen --config env-type.config.jsProgrammatic API
import { GeneratorService } from '@kitiumai/env-type-generator';
const service = new GeneratorService();
await service.generate({
envFiles: ['.env'],
outputPath: './types/env.d.ts',
parseTypes: true,
validationLib: 'zod',
validationOutput: './config/env.validator.ts',
});🎨 Framework Integration
Next.js
# Generate types
npx env-type-gen --env-files .env.local .env --parse-types
# Add to package.json
{
"scripts": {
"dev": "env-type-gen && next dev",
"build": "env-type-gen && next build"
}
}Vite
# Generate types
npx env-type-gen --parse-types
# Add to package.json
{
"scripts": {
"dev": "env-type-gen && vite",
"build": "env-type-gen && vite build"
}
}Node.js / Express
# Generate with Zod validation
npx env-type-gen --validation-lib zod --parse-types --strict
# Use in your app
import { env } from './config/env.validator';
const app = express();
app.listen(env.PORT); // Type-safe!📝 Generated Output Examples
Without Type Parsing
Input (.env):
DATABASE_URL=postgresql://localhost:5432/mydb
PORT=3000Output (env.d.ts):
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL?: string | undefined;
PORT?: string | undefined;
}
}
export declare const env: {
DATABASE_URL?: string;
PORT?: string;
};With Type Parsing
Input (.env):
DATABASE_URL=postgresql://localhost:5432/mydb
PORT=3000
ENABLE_DEBUG=true
CONFIG={"key":"value"}Output (env.d.ts):
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL?: string | undefined;
PORT?: number | undefined;
ENABLE_DEBUG?: boolean | undefined;
CONFIG?: object | undefined;
}
}
export declare const env: {
DATABASE_URL?: string;
PORT?: number;
ENABLE_DEBUG?: boolean;
CONFIG?: object;
};With Comments
Input (.env):
# Database connection string
DATABASE_URL=postgresql://localhost:5432/mydb
# Maximum number of connections
DATABASE_POOL_SIZE=10Output (env.d.ts):
declare namespace NodeJS {
interface ProcessEnv {
/** Database connection string */
DATABASE_URL?: string | undefined;
/** Maximum number of connections */
DATABASE_POOL_SIZE?: number | undefined;
}
}TypeScript Configuration
Add the generated types to your tsconfig.json:
{
"compilerOptions": {
"types": ["node"],
"typeRoots": ["./node_modules/@types", "./src/types"]
},
"include": ["src/**/*", "src/types/env.d.ts"]
}GitHub Actions
This repository includes comprehensive CI/CD workflows:
CI Workflow
Runs on every push and pull request to main/master branch:
- Linting: ESLint and Prettier checks
- Type Checking: TypeScript compilation
- Testing: Multi-version tests (Node 16, 18, 20) across OS (Ubuntu, Windows, macOS)
- Build: Ensures project builds successfully
- Integration Tests: End-to-end CLI testing with type generation and validation
Publish Workflow
Automatically publishes to npm on GitHub releases:
- Runs all quality checks
- Publishes with npm provenance for enhanced security
- Creates deployment summary
Security Workflows
- CodeQL: Weekly security scans for vulnerabilities
- Dependency Review: Automated review on pull requests
Adding to Your Project
Add similar CI/CD to your project using env-type-generator:
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx env-type-gen --parse-types
- run: npm testComparison with Other Tools
| Feature | env-type-generator | t3-env | envalid | ts-dotenv | | ----------------------- | ------------------ | ------ | ------- | --------- | | Auto-generate from .env | ✅ | ❌ | ❌ | ❌ | | Zero config | ✅ | ❌ | ❌ | ❌ | | Type inference | ✅ | ⚠️ | ⚠️ | ✅ | | Runtime validation | ✅ | ✅ | ✅ | ✅ | | Framework-agnostic | ✅ | ❌ | ✅ | ✅ | | Watch mode | ✅ | ❌ | ❌ | ❌ | | Active maintenance | ✅ | ✅ | ✅ | ❌ | | Weekly downloads | TBD | 501K | 200K | 3.6K |
Key Advantage: We're the only tool that auto-generates types from existing .env files without requiring manual schema definition.
🛠️ Troubleshooting
Types not updating in IDE
- Restart TypeScript server:
Cmd/Ctrl + Shift + P→ "TypeScript: Restart TS Server" - Ensure
env.d.tsis included intsconfig.json
Variables not being recognized
- Check that your .env file uses valid variable names (UPPERCASE_WITH_UNDERSCORES)
- Regenerate types:
npx env-type-gen - Verify output path matches your tsconfig includes
Watch mode not working
- Ensure you have write permissions in the output directory
- Check that the .env file path is correct
- Try using absolute paths instead of relative paths
Best Practices
Add to git ignore: Add generated files to
.gitignoresrc/types/env.d.ts src/config/env.validator.tsGenerate in pre-build: Add to your build pipeline
{ "scripts": { "prebuild": "env-type-gen", "build": "tsc" } }Use strict mode in production: Catch missing vars early
env-type-gen --strict --required DATABASE_URL API_KEYCombine with dotenv-expand: For variable interpolation
BASE_URL=https://api.example.com API_ENDPOINT=${BASE_URL}/v1
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
License
MIT © kitium-ai
Acknowledgments
Support
Made with ❤️ for the TypeScript community
