Ensures required environment variables exist, failing fast at startup if they are missing.
- ✅ Fail Fast: Throws clear errors if required environment variables are missing.
- ✅ Type Safe: Returns a typed object with your environment variables.
- ✅ Defaults: Supports default values for optional variables.
- ✅ Zero Dependencies: Lightweight and fast.
- ✅ Dual Support: Works with both ES Modules (ESM) and CommonJS (CJS).
npm install env-requiredRequire specific environment variables. If any are missing from process.env, requireEnv throws an error.
import { requireEnv } from 'env-required';
try {
const { DB_URL, JWT_SECRET } = requireEnv([
'DB_URL',
'JWT_SECRET',
]);
console.log('Connected to:', DB_URL);
} catch (error) {
// Error: Missing required environment variables: DB_URL, JWT_SECRET
console.error(error.message);
process.exit(1);
}You can provide a second argument with default values. If an environment variable is missing but has a default, it will use the default instead of throwing.
import { requireEnv } from 'env-required';
const { PORT, NODE_ENV } = requireEnv(
['NODE_ENV'], // Required
{ PORT: '3000' } // Optional with default
);
// If PORT is not in env, it validates successfully and returns '3000'
console.log(`Server running on port ${PORT} in ${NODE_ENV} mode`);const { requireEnv } = require('env-required');
const { API_KEY } = requireEnv(['API_KEY']);- required: Array of strings representing required environment variable names.
- defaults: (Optional) Object mapping variable names to default values.
- Returns: An object containing all requested variables (from env or defaults).
- Throws:
Errorif any variable inrequiredis missing fromprocess.env.
MIT
Author: Ahmer Arain