Skip to content

misbahafzal/env-safe-ts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

env-safe-ts

Type-safe environment variable loader for Node.js.

npm npm license

GitHub stars

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 defined

2. 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

About

A npm package to safely load environment variables in your projects, performs validation checks and graceful error handling on earlier stage.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors