1.0.1 • Published 5 months ago
env-type-safe v1.0.1
env-type-safe
A type-safe environment variable manager for Node.js applications with built-in validation and TypeScript support.
Features
- 🔒 Type Safety: Full TypeScript support with type inference
- ✅ Validation: Automatic type validation for strings, numbers, and booleans
- 📁 Environment Files: Load variables from
.env
files (using dotenv) - 🛡️ Runtime Safety: Throws helpful errors for missing or invalid variables
- 🔍 Debugging: Clear error messages for troubleshooting
- 🎯 Simple API: Easy to use with minimal setup
Installation
npm install env-type-safe dotenv
Note: dotenv
is a peer dependency and must be installed separately.
Quick Start
import { createEnvSafe } from 'env-type-safe';
// Define your environment schema
const env = createEnvSafe({
PORT: "number",
API_KEY: "string",
DEBUG: "boolean",
}, {
envFile: ".env" // Optional: path to .env file
});
// Type-safe access to variables
const port: number = env.get<number>("PORT"); // Returns number
const apiKey: string = env.get<string>("API_KEY"); // Returns string
const debug: boolean = env.get<boolean>("DEBUG"); // Returns boolean
// Get all variables at once
const allVars = env.getAll();
Schema Types
The package supports three types of environment variables:
Type | Description | Example |
---|---|---|
string | Any string value | API_KEY="xyz123" |
number | Numeric values (auto-converted from string) | PORT="3000" |
boolean | Boolean values (must be "true" or "false") | DEBUG="true" |
Error Handling
The package includes comprehensive error handling:
Missing Variables
// If DATABASE_URL is not defined: createEnvSafe({ DATABASE_URL: "string" }) // Error: Environment variable DATABASE_URL is missing
Invalid Types
// If PORT="not-a-number" in .env: createEnvSafe({ PORT: "number" }) // Error: Environment variable PORT must be a number
Invalid Boolean Values
// If DEBUG="yes" in .env: createEnvSafe({ DEBUG: "boolean" }) // Error: Environment variable DEBUG must be 'true' or 'false'
Best Practices
Define Schema Once
// config/env.ts export const envSchema = { NODE_ENV: "string", PORT: "number", DEBUG: "boolean", API_KEY: "string" }; export const env = createEnvSafe(envSchema);
Use Type Inference
// TypeScript will infer the correct types const { PORT, API_KEY, DEBUG } = env.getAll();
Environment File
PORT=3000 DEBUG=true API_KEY=your-secret-key
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
MIT
Author
MD Azadur Rahman