safe-env-manager
v1.0.0
Published
A tiny, zero-dependency utility to safely load, validate, and manage environment variables in Node.js.
Downloads
5
Maintainers
Readme
safe-env
A tiny, zero-dependency utility to safely load, validate, and manage environment variables in Node.js.
It ensures your application starts with a valid configuration, failing fast with clear error messages if any required variables are missing or malformed.
Problem
Manually checking process.env is error-prone and repetitive.
// The old way
const PORT = process.env.PORT || 3000;
if (!process.env.API_KEY) {
throw new Error("FATAL: Missing API_KEY!");
}This approach leads to scattered checks, inconsistent error handling, and silent bugs in production.
Solution
safe-env provides a clean, centralized schema to define your environment configuration.
// The new way with safe-env
const config = safeEnv({
API_KEY: { type: 'string', required: true },
PORT: { type: 'number', default: 8080 },
});Features
- ✅ Schema Validation: Define required and optional variables in one place.
- ❌ Fail-Fast: Throws a clear, readable error for missing variables.
- 🔄 Type Casting: Automatically converts variables to
number,boolean, andjson. - 🤫
.envSupport: Automatically loads variables from a.envfile for local development. - 💡 Zero Dependencies: Tiny, fast, and secure. No external packages.
- 🔒 Immutable: The returned config object is frozen to prevent runtime mutations.
- 🚀 TypeScript Ready: Fully typed with intelligent inference.
Installation
npm install safe-env-managerUsage
- Create a configuration file, for example
src/config.ts. - Define your schema and export the validated config.
src/config.ts
import safeEnv from 'safe-env-manager';
const config = safeEnv({
NODE_ENV: { type: 'string', default: 'development' },
PORT: { type: 'number', default: 3000 },
HOST: { type: 'string', default: '0.0.0.0' },
// Required variables
JWT_SECRET: { type: 'string', required: true },
DATABASE_URL: { type: 'string', required: true },
// Typed variables
ENABLE_FEATURE_X: { type: 'boolean', default: false },
CORS_ORIGINS: { type: 'json', required: true },
});
export default config;If JWT_SECRET is missing, the application will immediately crash on startup with:
❌ Missing required environment variable(s): JWT_SECRETNow you can import your strongly-typed config anywhere in your app:
src/server.ts
import config from './config';
console.log(`Server running in ${config.NODE_ENV} mode.`);
// config.PORT is a 'number', not a 'string | undefined'
app.listen(config.PORT, config.HOST, () => {
console.log(`Server listening on http://${config.HOST}:${config.PORT}`);
});CLI Checker
You can verify your environment without running the full application. This is great for CI/CD pipelines or deployment scripts.
- Create a
safe-env.config.jsfile in your project root:
safe-env.config.js
const schema = {
JWT_SECRET: { type: 'string', required: true },
DATABASE_URL: { type: 'string', required: true },
PORT: { type: 'number', default: 3000 },
};
module.exports = { schema };- Run the checker:
npx safe-env-check- On success, it will print:
✅ All required environment variables are present and valid.and exit with code0. - On failure, it will print the missing variables error and exit with code
1.
API
safeEnv(schema)
schema
An object where each key corresponds to an environment variable. The value is an options object with the following properties:
type: ('string'|'number'|'boolean'|'json') The target type for the variable.required: (boolean, optional) Iftrue, the process will exit if the variable is not defined.default: (any, optional) A fallback value to use if the variable is not set. The type should match the specifiedtype.
