env-safe-ts
v1.0.3
Published
Type-safe environment variable loader for Node.js.
Maintainers
Readme
env-safe-ts
Type-safe environment variable loader for Node.js.
Install
npm install env-safe-ts
Usage
import 'dotenv/config';
import { loadEnv } from 'env-safe-ts';
export const env = loadEnv({
PORT: { type: 'number', required: true },
SLACK_API_KEY: { type: 'string', required: true },
TYPE: {
type: 'enum',
required: false,
values: ['development', 'production']
}
});
Common Pitfalls & Best Practices
1. Missing vs Empty Environment Variables
env-safe-ts treats both missing variables and empty strings ("") as missing values.
This is intentional.
DATABASE_URL=is considered the same as:
# DATABASE_URL is not defined2. Not All Services Use All Environment Variables
In large systems, not all features or services are enabled at the same time.
❌ Anti-pattern
loadEnv({
PAYMENTS_API_KEY: { type: 'string', required: true },
SEARCH_API_KEY: { type: 'string', required: true },
});This assumes everything is always enabled.
✅ Recommended patterns
Service-scoped env schemas
// payments/env.ts
export const paymentsEnv = loadEnv({
PAYMENTS_API_KEY: { type: 'string', required: true },
});Load envs only when the service or feature is enabled.
3. Keep a Canonical .env.example
env-safe-ts enforces correctness at runtime, while .env.example documents expectations.
4. Important Note: Environment Loading
env-safe-ts does not load .env files.
This is intentional.
You must load environment variables before calling loadEnv, for example:
import 'dotenv/config';Author
Created and maintained by Misbah Afzal
GitHub: https://github.com/misbahafzal
LICENSE
MIT © Misbah Afzal
