A TypeScript-first library for type-safe environment variable parsing and validation with full IntelliSense and optional logging.
- π Type-safe: Full TypeScript support with automatic type inference
- π Schema-based: Define environment variables with a clear schema
- β Validation: Built-in and custom validators
- π― IntelliSense: Autocomplete for environment variable names
- π§ Flexible: Supports
string,number,boolean, andenum - π Error handling: Throw or log warnings based on configuration
- π Zero dependencies: Lightweight, focused, and portable with zero dependencies (only dotenv for peer)
β οΈ Note: This package is Node-first. Full type safety works in Node, Nest.js, and Express. For Next.js or browser environments, variables must be exposed viaNEXT_PUBLIC_*and are limited to strings. (Not recommended for next js till now)
npm install env-typed-guardimport defineEnv from 'env-typed-guard';
const env = defineEnv({
PORT: { type: 'number', defaultValue: 3000 },
NODE_ENV: {
type: 'enum',
validValues: ['development', 'production', 'test'],
defaultValue: 'development'
},
DATABASE_URL: { type: 'string' }, // Required
DEBUG: { type: 'boolean', defaultValue: false }
});
console.log(`Server running on port ${env.PORT}`);
console.log(`Environment: ${env.NODE_ENV}`);
console.log(`Debug mode: ${env.DEBUG}`);Parses and validates environment variables based on a schema.
schemaβ Object defining environment variables and their types.configβ Optional configuration:
| Property | Type | Required | Description |
|---|---|---|---|
type |
'string', 'number', 'boolean', 'enum' |
β Yes | The type of the environment variable |
defaultValue |
same as type | β No | Default value if the variable is not set |
validate |
(value) => boolean | string |
β No | Custom validation function; return true or error message |
validValues |
string[] |
β No* | Required if type is 'enum'; allowed values |
*Only required for enum type variables.
| Option | Type | Default | Description |
|---|---|---|---|
debugMode |
boolean |
false |
Enable debug logging of parsed environment variables |
throw |
boolean |
true |
Throw errors on validation failure (if false, logs only) |
const env = defineEnv({
API_KEY: { type: 'string', defaultValue: 'dev-key' }
});const env = defineEnv({
PORT: { type: 'number', defaultValue: 3000 }
});
// PORT=8080 β parsed as number 8080const env = defineEnv({
DEBUG: { type: 'boolean', defaultValue: false }
});
// Accepts: 'true', 'false', '1', '0' (case insensitive)const env = defineEnv({
LOG_LEVEL: {
type: 'enum',
validValues: ['debug', 'info', 'warn', 'error'],
defaultValue: 'info'
}
});
// Type: 'debug' | 'info' | 'warn' | 'error'const env = defineEnv({
PASSWORD: {
type: 'string',
validate: (val) => val.length >= 8 || 'Password must be at least 8 chars'
},
PORT: {
type: 'number',
defaultValue: 3000,
validate: (val) => (val >= 1000 && val <= 65535) || 'Port must be 1000β65535'
}
});const env = defineEnv({
DATABASE_URL: { type: 'string' }, // Required
CACHE_TTL: { type: 'number', defaultValue: 300 } // Optional
});- Node/Nest.js/Express: Full types supported.
- Next.js client: Only strings allowed; use
NEXT_PUBLIC_*prefix: (Not recommended till now)
const nextConfig = {
env: {
NEXT_PUBLIC_API_URL: env.API_URL, // string only
}
};try {
const env = defineEnv({ REQUIRED_VAR: { type: 'string' } });
} catch (err) {
console.error('Env validation failed:', err.message);
process.exit(1);
}
// Or disable throwing
const env = defineEnv({ REQUIRED_VAR: { type: 'string' } }, { throw: false });const env = defineEnv({
PORT: { type: 'number', defaultValue: 3000 }
}, { debugMode: true });
// Output:
// Environment variables:
// PORT=3000 (using default)- Use
as constfor type literals:
type: 'string' as const- Validate early in your app startup:
const env = defineEnv(schema); // Top of main file- Use meaningful validation messages:
validate: (value) => value > 0 || 'Must be positive'- Provide defaults for optional vars:
TIMEOUT: { type: 'number', defaultValue: 5000 }DATABASE_URL=postgres://user:pass@localhost:5432/db
PORT=8080
DEBUG=true
NODE_ENV=production- Type inference from schema
- IntelliSense autocomplete
- Compile-time type checking
- Clear error messages
- β Node.js
- β Nest.js
- β Express.js
- π¨ Next.js (server-side only, client limited to strings)
Currently, there are no active contribution opportunities. However, if you come across any issues, feel free to raise them in the GitHub Issues section.