env-guard-dev
v1.0.0
Published
Validate and auto-fill environment variables at startup
Maintainers
Readme
env-guard 🛡️
A lightweight and strict environment variable validator for Node.js apps. Ensure your app fails fast if required environment variables are missing, or auto-fill them with defaults.
Features
- 🛑 Fail Fast: Terminates the process aggressively if required
process.envkeys are missing. - ⚙️ Auto-fill Defaults: Automatically sets fallback values if keys are not provided.
- 📦 Zero Dependencies: Extremely light.
- 🚀 Built for Modern Node: Written in TypeScript, ESM by default.
Installation
npm install env-guardUsage
Import validateEnv at the very beginning of your application (e.g., index.js, server.js or main.ts), to ensure all environment variables are verified before the rest of your app runs.
import { validateEnv } from 'env-guard';
validateEnv({
PORT: { required: true, default: "3000" },
DATABASE_URL: { required: true },
API_KEY: { required: false }
});
// If DATABASE_URL is missing, the app will log an error and exit with code 1.
// If PORT is missing, process.env.PORT will be set to "3000".
console.log(`Server starting on port ${process.env.PORT}`);API
validateEnv(schema: EnvSchema): void
Validates the process.env against the provided schema.
schema: An object where keys are the environment variable names and values are objects containing:required(boolean): Whether the environment variable must be present.default(string - optional): A fallback value to use if the environment variable is omitted or empty.
If validation fails, env-guard will output the missing keys to console.error and call process.exit(1).
License
MIT
