@patrickaigbogunoti/x-env
v0.2.139
Published
Typed .env manager for modern TypeScript projects (Vite, Next.js, etc.)
Maintainers
Readme
X-Env
🚀 Modern, type-safe environment variable management for TypeScript projects
X-Env eliminates the guesswork and runtime errors of working with environment variables by providing full TypeScript support, autocompletion, and compile-time safety for your .env files.
🎯 Problems X-Env Solves
❌ Before X-Env
// No type safety - typos cause runtime errors
const apiUrl = process.env.NEXT_PUBLC_API_URL; // Typo!
const secret = process.env.SECRET_KEY; // Might be undefined
// No autocompletion - you have to remember variable names
const dbUrl = process.env.DATABASE_URL;
// Client/server confusion - accidentally exposing secrets
if (typeof window !== 'undefined') {
// This could expose private keys!
const privateKey = process.env.PRIVATE_KEY;
}✅ After X-Env
import { getClientEnv, getServerEnv } from './lib/env-helpers';
// Full type safety and autocompletion
const apiUrl = getClientEnv('NEXT_PUBLIC_API_URL'); // ✅ Autocomplete works!
const secret = getServerEnv('SECRET_KEY'); // ✅ Server-only, type-safe
// Compile-time errors for typos
const badUrl = getClientEnv('NEXT_PUBLC_API_URL'); // ❌ TypeScript error!
// Runtime protection
const privateKey = getServerEnv('PRIVATE_KEY'); // ❌ Throws on client🌟 Key Features
- 🎯 Type Safety: Full TypeScript support with autocompletion for all your env variables
- 🔒 Client/Server Safety: Prevents accidentally exposing server secrets to the browser
- ⚡ Zero Config: Works out of the box with sensible defaults
- 🔄 Auto-Generated Types: Scans your
.envfiles and generates TypeScript definitions - 🚀 Framework Agnostic: Works with Next.js, Vite, Remix, and more
- 📝 IntelliSense: Get autocomplete suggestions for all your environment variables
📦 Installation
npm install @patrickaigbogunoti/x-env
# or
pnpm add @patrickaigbogunoti/x-env
# or
yarn add @patrickaigbogunoti/x-env🚀 Quick Start
1. Initialize X-Env in your project
npx x-env initThis creates:
config/env/index.ts- Your configuration filelib/env-helpers.ts- Type-safe helper functions- Updates your
tsconfig.jsonwith proper paths
2. Configure your environment files
// config/env/index.ts
import { defineConfig } from '@patrickaigbogunoti/x-env';
export default defineConfig({
envFiles: ['.env', '.env.local', '.env.production'],
publicPrefix: ['NEXT_PUBLIC_', 'VITE_'], // Support multiple prefixes
generated: 'x-env.d.ts',
entryPoints: ['next.config.ts', 'vite.config.ts'] // Multiple entry points
});3. Set up your .env file
# .env
DATABASE_URL=postgresql://localhost:5432/mydb
SECRET_KEY=super-secret-key
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_APP_NAME=My App4. Generate types from your environment variables
npx x-env generateThis scans your .env files, creates TypeScript definitions for all your variables, and automatically injects the Load() function into your configured entry points.
5. Use type-safe environment variables
// lib/algolia.ts (server-side)
import { getServerEnv, getClientEnv } from './lib/env-helpers';
// Server-only variables (private)
const adminKey = getServerEnv('ALGOLIA_ADMIN_KEY'); // ✅ Type-safe
const dbUrl = getServerEnv('DATABASE_URL');
// Client-safe variables (public)
const appId = getClientEnv('NEXT_PUBLIC_ALGOLIA_APP_ID');
const searchKey = getClientEnv('NEXT_PUBLIC_ALGOLIA_SEARCH_KEY');6. Load environment variables in your config
The generate command automatically injects the Load() function into your configured entry points. If you need to add it manually:
// next.config.js (already injected by generate command)
import { Load } from '@patrickaigbogunoti/x-env/server';
Load(); // Loads your .env files into process.env
/** @type {import('next').NextConfig} */
const nextConfig = {
// your config
};
export default nextConfig;💡 Usage Examples
Next.js App Router
// app/components/search.tsx
'use client';
import { getClientEnv } from '@/lib/env-helpers';
export function SearchComponent() {
// ✅ Type-safe, autocomplete works
const apiUrl = getClientEnv('NEXT_PUBLIC_API_URL');
// ❌ This would throw at runtime (server-only variable)
// const secret = getServerEnv('SECRET_KEY');
return <div>Search powered by {apiUrl}</div>;
}// app/api/users/route.ts
import { getServerEnv } from '@/lib/env-helpers';
export async function GET() {
// ✅ Server-only, secure
const dbUrl = getServerEnv('DATABASE_URL');
const secretKey = getServerEnv('SECRET_KEY');
// Connect to database using dbUrl...
return Response.json({ users: [] });
}Vite + React
// vite.config.ts
import { defineConfig } from 'vite';
import { Load } from '@patrickaigbogunoti/x-env/server';
Load(); // Load environment variables
export default defineConfig({
// your vite config
});// src/api/client.ts
import { getClientEnv } from './lib/env-helpers';
const apiClient = axios.create({
baseURL: getClientEnv('VITE_API_URL'), // ✅ Type-safe
timeout: 5000
});🛠️ Available Commands
npx x-env init- Initialize X-Env in your projectnpx x-env generate- Generate TypeScript definitions from your .env files and inject Load() into entry pointsnpx x-env watch- Watch for changes and auto-regenerate types
🎛️ Configuration Options
// config/env/index.ts
export default defineConfig({
// Environment files to load (in order)
envFiles: ['.env', '.env.local', '.env.production'],
// Prefixes for public environment variables (supports multiple)
publicPrefix: ['NEXT_PUBLIC_', 'VITE_', 'PUBLIC_'],
// Output file for generated types
generated: 'x-env.d.ts',
// Entry points where Load() should be auto-injected
entryPoints: ['next.config.ts', 'vite.config.ts', 'app.ts']
});🔐 Security Features
X-Env helps prevent common security mistakes:
- Server-only protection:
getServerEnv()throws an error if called in browser code - Public/private separation: Only variables with your
publicPrefixare accessible viagetClientEnv() - Compile-time checks: TypeScript catches typos and undefined variables before runtime
📚 Framework Support
X-Env works with any TypeScript project, with built-in support for:
- ✅ Next.js (App Router & Pages Router)
- ✅ Vite (React, Vue, Svelte)
- ✅ Remix
- ✅ Nuxt (coming soon)
- ✅ SvelteKit (coming soon)
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT License - see LICENSE for details.
