@se-oss/env
v1.1.0
Published
A universal, type-safe environment variable loader for Node.js, Edge, and Browser environments.
Maintainers
Readme
@se-oss/env is a universal, type-safe environment variable loader for Node.js, Edge, and Browser environments, powered by Standard Schema.
Benefits
- Universal Support: Run across all environments, such as Node.js, Vercel Edge, Cloudflare Workers, or the Browser, using a single API.
- Schema Validation: Catch configuration errors at startup using Zod, Valibot, ArkType, or any Standard Schema validator.
- Strict Type Safety: Enjoy full TypeScript autocompletion and inferred types for your environment variables.
- Immutable Config: Returns a frozen object to prevent accidental runtime modifications.
- Smart Defaults: Automatically treats empty strings as
undefinedto ensure your defaults are correctly applied. - Flexible Composition: Merge and extend multiple environment configurations effortlessly.
📦 Installation
npm install @se-oss/envpnpm
pnpm install @se-oss/envyarn
yarn add @se-oss/env📖 Usage
Node.js + Zod
Load environment variables with automatic .env support and validation.
import { createEnv } from '@se-oss/env';
import { z } from 'zod';
export const env = createEnv({
schema: {
NODE_ENV: z
.enum(['development', 'production', 'test'])
.default('development'),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url(),
},
runtimeEnv: process.env,
dotenv: true,
emptyStringAsUndefined: true,
});Vite / Browser
Use in frontend projects by passing the specific runtime environment object.
import { createEnv } from '@se-oss/env';
import { z } from 'zod';
export const env = createEnv({
schema: {
VITE_API_URL: z.string().url(),
VITE_APP_TITLE: z.string().default('My App'),
},
runtimeEnv: import.meta.env,
});Composition
Merge multiple environment configurations to maintain modularity.
const baseEnv = createEnv({
schema: { SHARED_KEY: z.string() },
runtimeEnv: process.env,
});
const appEnv = createEnv({
schema: { APP_KEY: z.string() },
runtimeEnv: process.env,
extends: [baseEnv],
});🌍 Universal Compatibility
Unlike traditional env loaders, @se-oss/env does not implicitly rely on process.env. By requiring a runtimeEnv object, it can run anywhere:
- Node.js: Pass
process.env. - Vite: Pass
import.meta.env. - Cloudflare Workers: Pass the
envobject from the handler. - Next.js: Pass
process.env.
🔗 Relevant
- process-venv: If you need strict environment isolation and security for Node.js. It prevents unintended access by third-party dependencies by isolating your secrets from the global
process.env.
🤝 Contributing
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub.
Thanks again for your support, it is much appreciated! 🙏
License
MIT © Shahrad Elahi and contributors.
