Fail-fast environment variable validation
npm install @axshat.co.in/env-safebash
npm install @axshat.co.in/env-safe
``
or
`bash
yarn add @axshat.co.in/env-safe
`
---
Code Examples
$3
`ts
import { envSafe } from "@axshat.co.in/env-safe";
const env = envSafe({
DATABASE_URL: "string",
PORT: "number",
DEBUG: "boolean",
});
`
---
$3
`ts
const env = envSafe({
PORT: { type: "number", default: 3000 },
});
`
---
$3
`ts
const env = envSafe({
LOG_LEVEL: { type: "string", optional: true },
});
`
---
$3
`ts
const env = envSafe({
NODE_ENV: {
type: "enum",
values: ["development", "production"],
},
});
`
---
$3
`ts
const env = envSafe({
JWT_SECRET: {
type: "string",
validate: (value) => value.length >= 16,
},
});
`
---
$3
`ts
const env = envSafe({
DATABASE_URL: "string",
PORT: { type: "number", default: 3000 },
NODE_ENV: {
type: "enum",
values: ["development", "production"],
},
JWT_SECRET: {
type: "string",
validate: (v) => v.length >= 16,
},
});
`
---
TypeScript Interface
$3
`ts
export type EnvType = "string" | "number" | "boolean" | "enum";
`
---
$3
`ts
export interface EnvRule {
type: EnvType;
default?: T;
optional?: boolean;
values?: readonly string[];
validate?: (value: T) => boolean;
}
`
---
$3
`ts
export type EnvSchema = Record;
`
---
$3
`ts
export function envSafe(
schema: T
): {
[K in keyof T]: any;
};
`
---
Error Output
Missing variable:
`txt
❌ Missing environment variable: DATABASE_URL
`
Invalid value:
`txt
❌ Validation failed for: JWT_SECRET
`
---
Why @axshat.co.in/env-safe?
Accessing environment variables directly is unsafe:
`ts
process.env.API_KEY! // unsafe
``