env-sentry-lib
v1.1.5
Published
Type-safe environment variable validation with Zod
Maintainers
Readme
env-sentry-lib
Type-safe environment variable validation for Node.js with Zod.
Why?
Environment variables are loosely typed and error-prone. env-sentry-lib gives you:
- ✅ Type Safety - Full TypeScript inference from your schema
- ✅ Runtime Validation - Catch configuration errors at startup
- ✅ Better Errors - Helpful error messages that tell you exactly what's wrong
- ✅ Zero Config - Works out of the box with any Node.js project
Installation
npm install env-sentry-lib zod
# or
pnpm add env-sentry-lib zod
# or
yarn add env-sentry-lib zodQuick Start
import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';
// Define your environment schema
const env = createEnv({
// Server config
PORT: z.string().default('3000').transform(Number),
HOST: z.string().default('localhost'),
// Database
DATABASE_URL: z.url(),
// API Keys
API_KEY: z.string().min(32),
// Feature flags
NODE_ENV: z
.enum(['development', 'production', 'test'])
.default('development'),
});
// Use with full type safety!
const port: number = env.PORT; // TypeScript knows this is a number
const dbUrl: string = env.DATABASE_URL; // TypeScript knows this is a string
// Start your server
console.log(`Server running on ${env.HOST}:${env.PORT}`);Features
Type-Safe by Default
TypeScript automatically infers the correct types from your schema:
const env = createEnv({
PORT: z.string().transform(Number),
ENABLED: z.boolean(),
TAGS: z.array(z.string()),
});
env.PORT; // type: number
env.ENABLED; // type: boolean
env.TAGS; // type: string[]Default Values
Provide defaults for optional configuration:
const env = createEnv({
PORT: z.string().default('3000').transform(Number),
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});
// If PORT is not set, uses 3000
// If LOG_LEVEL is not set, uses 'info'Optional Values
Some values don't need defaults:
const env = createEnv({
SENTRY_DSN: z.url().optional(),
DEBUG_MODE: z.boolean().optional(),
});
env.SENTRY_DSN; // type: string | undefined
env.DEBUG_MODE; // type: boolean | undefinedHelpful Error Messages
When validation fails, you get actionable error messages:
Environment validation failed.
The application cannot start due to invalid environment variables.
Missing required variables:
• DATABASE_URL
Action: Define these variables in your environment.API Reference
createEnv(schema)
Creates a validated, type-safe environment object.
Parameters:
schema- An object where keys are environment variable names and values are Zod schemas
Returns:
- A validated object with the same keys, typed according to the Zod schemas
Throws:
EnvValidationError- When validation fails
Example:
const env = createEnv({
PORT: z.string().transform(Number),
API_KEY: z.string(),
});EnvValidationError
Custom error class thrown when environment validation fails.
import { createEnv, EnvValidationError } from 'env-sentry-lib';
try {
const env = createEnv({ PORT: z.string() });
} catch (error) {
if (error instanceof EnvValidationError) {
console.error(error.message);
}
}Common Patterns
Number Validation
const env = createEnv({
PORT: z.string().transform(Number).pipe(z.number().min(1000).max(65535)),
MAX_CONNECTIONS: z.string().default('100').transform(Number),
});URL Validation
const env = createEnv({
DATABASE_URL: z.url(),
REDIS_URL: z.url().optional(),
API_ENDPOINT: z.url().startsWith('https://'),
});Enum Values
const env = createEnv({
NODE_ENV: z.enum(['development', 'staging', 'production']),
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']),
});Boolean Values
const env = createEnv({
DEBUG: z.string().transform((val) => val === 'true'),
ENABLE_CACHE: z
.string()
.transform((val) => val === 'true')
.pipe(z.boolean()),
});Array Values
const env = createEnv({
ALLOWED_ORIGINS: z.string().transform((val) => val.split(',')),
FEATURE_FLAGS: z
.string()
.transform((val) => val.split(','))
.pipe(z.array(z.string())),
});Framework Examples
Express.js
import express from 'express';
import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';
const env = createEnv({
PORT: z.string().default('3000').transform(Number),
DATABASE_URL: z.url(),
});
const app = express();
app.listen(env.PORT, () => {
console.log(`Server running on port ${env.PORT}`);
});Next.js
// config/env.ts
import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';
export const env = createEnv({
// Server-side only
DATABASE_URL: z.url(),
// Client-side (must start with NEXT_PUBLIC_)
NEXT_PUBLIC_API_URL: z.url(),
});Fastify
import fastify from 'fastify';
import { createEnv } from 'env-sentry';
import { z } from 'zod';
const env = createEnv({
HOST: z.string().default('0.0.0.0'),
PORT: z.string().default('3000').transform(Number),
});
const server = fastify();
server.listen({ host: env.HOST, port: env.PORT });Comparison
| Feature | env-sentry-lib | envalid | dotenv | zod | t3-env | | ------------------ | -------------- | ------- | ------ | --- | ------ | | Type Inference | ✅ | ✅ | ❌ | ✅ | ✅ | | Runtime Validation | ✅ | ✅ | ❌ | ✅ | ✅ | | Helpful Errors | ✅ | ⚠️ | ❌ | ⚠️ | ✅ | | Framework Agnostic | ✅ | ✅ | ✅ | ✅ | ❌ | | Modern (2024+) | ✅ | ❌ | ✅ | ✅ | ✅ | | Zero Config | ✅ | ✅ | ✅ | ❌ | ❌ |
Roadmap
- [ ] Secret masking (v0.2.0)
- [ ] .env file loading (v0.2.0)
- [ ] CLI tools (v0.3.0)
- [ ] Cloud secrets integration (v0.4.0)
- [ ] Documentation site (v1.0.0)
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License — see the LICENSE.
Author
Built with ❤️ by mandy8055
