Type-safe environment variable loader for Node.js.
npm install env-safe-ts
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']
}
});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 defined
In large systems, not all features or services are enabled at the same time.
loadEnv({
PAYMENTS_API_KEY: { type: 'string', required: true },
SEARCH_API_KEY: { type: 'string', required: true },
});
This assumes everything is always enabled.
✅ Recommended patterns
// payments/env.ts
export const paymentsEnv = loadEnv({
PAYMENTS_API_KEY: { type: 'string', required: true },
});
Load envs only when the service or feature is enabled.
env-safe-ts enforces correctness at runtime, while .env.example documents expectations.
env-safe-ts does not load .env files.
This is intentional.
You must load environment variables before calling loadEnv, for example:
import 'dotenv/config';
Created and maintained by Misbah Afzal
GitHub: https://github.com/misbahafzal
MIT © Misbah Afzal