env-typed-guard
A TypeScript-first library for type-safe environment variable parsing and validation with full IntelliSense and optional logging.
Features
🔒 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 dotenv as a peer dependency
⚠️ Note — This package is Node-first. Full type safety works in Node.js, NestJS, and Express. For Next.js client code, the documented setup uses
NEXT_PUBLIC_*variables as strings. Next.js client use is currently discouraged.
Installation
npm install env-typed-guardQuick Start
import { 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}`);API
defineEnv(schema, config?)
Parses and validates environment variables based on a schema.
Parameters
schema— Object defining environment variables and their types.config— Optional configuration.
Schema
PropertyTypeRequiredDescriptiontype'string', 'number', 'boolean', 'enum'YesThe type of the environment variablekeystringNoSource environment variable name if it differs from the schema keyisSecretbooleanNoMasks the value in debug logs as ***********defaultValueSame as the selected typeNoDefault value when the variable is unsetvalidate(value) => boolean | stringNoCustom validator that returns true or an error messagevalidValuesstring[]For enum onlyAllowed enum values
Configuration (config)
OptionTypeDefaultDescriptiondebugModebooleanfalseEnable debug logging of parsed environment variablesthrowbooleantrueThrow on validation failure. Set to false to log only.
Types Supported
String
const env = defineEnv({
API_KEY: { type: 'string', defaultValue: 'dev-key' }
});Number
const env = defineEnv({
PORT: { type: 'number', defaultValue: 3000 }
});
// PORT=8080 → parsed as number 8080Boolean
const env = defineEnv({
DEBUG: { type: 'boolean', defaultValue: false }
});
// Accepts: 'true', 'false', '1', '0' (case insensitive)Enum
const env = defineEnv({
LOG_LEVEL: {
type: 'enum',
validValues: ['debug', 'info', 'warn', 'error'],
defaultValue: 'info'
}
});
// Type: 'debug' | 'info' | 'warn' | 'error'Advanced Usage
Built-in Presets
You can use built-in presets for common schema fields.
import { defineEnv, presets } from 'env-typed-guard';
const env = defineEnv({
NODE_ENV: presets.nodeEnv(),
PORT: presets.port(3000),
DEBUG: presets.boolean(false),
API_KEY: presets.secret(),
});presets.nodeEnv(defaultValue?)— Enum ofdevelopment | production | testpresets.port(defaultValue?)— Number with built-in port range validationpresets.boolean(defaultValue?)— Booleanpresets.secret(defaultValue?)— String withisSecret: true
Custom Validation
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'
}
});Optional vs Required Variables
const env = defineEnv({
DATABASE_URL: { type: 'string' }, // Required
CACHE_TTL: { type: 'number', defaultValue: 300 } // Optional
});Alias a Source Env Key
Use key when the actual environment variable name differs from your app-facing key.
const env = defineEnv({
ENV_KEY: {
type: 'string',
key: 'NEXT_PUBLIC_ENV_KEY'
}
});
// Reads process.env.NEXT_PUBLIC_ENV_KEY
// Access in app as env.ENV_KEYHide Secret Values in Debug Logs
Set isSecret: true to mask values in terminal output when debugMode is enabled.
const env = defineEnv({
SECRET_TOKEN: {
type: 'string',
isSecret: true
}
}, { debugMode: true });
// Debug output:
// SECRET_TOKEN=***********Node vs Client (Next.js)
Node.js, NestJS, and Express support all documented types.
Next.js client uses strings with the
NEXT_PUBLIC_*prefix in this setup. Client use is currently discouraged.
const nextConfig = {
env: {
NEXT_PUBLIC_API_URL: env.API_URL, // string only
}
};Error Handling
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 });Debug Mode
const env = defineEnv({
PORT: { type: 'number', defaultValue: 3000 }
}, { debugMode: true });
// Output:
// Environment variables:
// PORT=3000 (using default)Best Practices
Use
as constfor type literals.JavaScript type: 'string' as constValidate early in your app startup.
JavaScript const env = defineEnv(schema); // Top of main fileUse meaningful validation messages.
JavaScript validate: (value) => value > 0 || 'Must be positive'Provide defaults for optional variables.
JavaScript TIMEOUT: { type: 'number', defaultValue: 5000 }
Environment Variable Examples
DATABASE_URL=postgres://user:pass@localhost:5432/db
PORT=8080
DEBUG=true
NODE_ENV=productionTypeScript Integration
Type inference from the schema
IntelliSense autocomplete
Compile-time type checking
Clear error messages
Tested Environments
✅ Node.js
✅ NestJS
✅ Express.js
🟨 Next.js (server-side only, client limited to strings)
Contributing
Currently, there are no active contribution opportunities. If you come across any issues, feel free to raise them in the GitHub Issues section.