.env.example filesnpm i @osmn-byhn/envguard
import { loadEnv } from '@osmn-byhn/envguard';
const schema = {
PORT: "number",
DATABASE_URL: "string",
DEBUG: "boolean",
};
const env = loadEnv(schema);
console.log(env.PORT); // 3000 (number)
console.log(env.DATABASE_URL); // "postgresql://..." (string)
console.log(env.DEBUG); // true (boolean)
import { loadEnv } from '@osmn-byhn/envguard';
import { EnvSchema } from '@osmn-byhn/envguard';
const schema: EnvSchema = {
PORT: "number",
DATABASE_URL: "string",
};
const env = loadEnv(schema);
"string" for required strings, or
"string?" for optional
strings.
const schema = {
API_KEY: "string", // Required
OPTIONAL_KEY: "string?", // Optional
};
// .env
// API_KEY=my-secret-key
// OPTIONAL_KEY=optional-value (or omit this line)
const env = loadEnv(schema);
console.log(env.API_KEY); // "my-secret-key" (string)
console.log(env.OPTIONAL_KEY); // "optional-value" or undefined
const schema = {
PORT: "number",
TIMEOUT: "number?",
};
// .env
// PORT=3000
// TIMEOUT=5000
const env = loadEnv(schema);
console.log(env.PORT); // 3000 (number, not string)
console.log(typeof env.PORT); // "number"
PORT=abc → Throws error:
[EnvGuard] PORT must be a
number"true", "1" (case-insensitive) as true, everything else as false.
const schema = {
DEBUG: "boolean",
ENABLE_FEATURE: "boolean?",
};
// .env
// DEBUG=true
// ENABLE_FEATURE=1
const env = loadEnv(schema);
console.log(env.DEBUG); // true (boolean)
console.log(env.ENABLE_FEATURE); // true (boolean)
true, True, TRUE, 1 → truefalse, False, FALSE, 0, "", or any other value → falseconst schema = {
API_BASE_URL: "url",
WEBHOOK_URL: "url?",
};
// .env
// API_BASE_URL=https://api.example.com
// WEBHOOK_URL=https://webhook.example.com/callback
const env = loadEnv(schema);
console.log(env.API_BASE_URL); // "https://api.example.com"
API_BASE_URL=not-a-url →
Throws error: [EnvGuard]
API_BASE_URL must be a valid URLconst schema = {
ADMIN_EMAIL: "email",
SUPPORT_EMAIL: "email?",
};
// .env
// [email protected]
// [email protected]
const env = loadEnv(schema);
console.log(env.ADMIN_EMAIL); // "[email protected]"
ADMIN_EMAIL=invalid-email →
Throws error: [EnvGuard]
ADMIN_EMAIL must be a valid emailconst schema = {
NODE_ENV: ["development", "production", "test"],
LOG_LEVEL: ["debug", "info", "warn", "error"],
};
// .env
// NODE_ENV=production
// LOG_LEVEL=info
const env = loadEnv(schema);
console.log(env.NODE_ENV); // "production"
console.log(env.LOG_LEVEL); // "info"
NODE_ENV=staging →
Throws error: [EnvGuard] Invalid
value for NODE_ENV: staging, allowed: development, production,
testconst schema = {
CONFIG: "json",
FEATURE_FLAGS: "json?",
};
// .env
// CONFIG={"timeout":5000,"retries":3}
// FEATURE_FLAGS={"feature1":true,"feature2":false}
const env = loadEnv(schema);
console.log(env.CONFIG); // { timeout: 5000, retries: 3 } (object)
console.log(env.FEATURE_FLAGS); // { feature1: true, feature2: false } (object)
CONFIG={invalid json →
Throws error: [EnvGuard] CONFIG
must be a valid JSONconst schema = {
ALLOWED_ORIGINS: "array",
FEATURES: "array?",
};
// .env
// ALLOWED_ORIGINS=http://localhost:3000,https://example.com,https://app.example.com
// FEATURES=feature1,feature2,feature3
const env = loadEnv(schema);
console.log(env.ALLOWED_ORIGINS); // ["http://localhost:3000", "https://example.com", "https://app.example.com"]
console.log(env.FEATURES); // ["feature1", "feature2", "feature3"]
const schema = {
START_DATE: "date",
END_DATE: "date?",
};
// .env
// START_DATE=2024-01-01
// END_DATE=2024-12-31
const env = loadEnv(schema);
console.log(env.START_DATE); // Date object: 2024-01-01T00:00:00.000Z
console.log(env.START_DATE instanceof Date); // true
START_DATE=invalid-date
→ Throws error: [EnvGuard]
START_DATE must be a valid dateconst schema = {
SECRET_TOKEN: {
type: "string",
pattern: /^[A-Za-z0-9]{32,}$/,
description: "32 characters or longer alphanumeric token",
error: (err) => {
console.error("Custom error handler:", err.message);
process.exit(1);
},
required: true,
},
LOG_LEVEL: {
type: ["debug", "info", "warn", "error"],
default: "info",
description: "Log level",
error: (err) => console.error(err),
},
API_VERSION: {
type: "string",
pattern: /^v\d+\.\d+\.\d+$/,
default: "v1.0.0",
description: "API version in semver format",
},
};
// .env
// SECRET_TOKEN=MySuperSecretToken12345678901234567890
// LOG_LEVEL=debug (or omit for default "info")
// API_VERSION=v2.1.0
type: The base type
(string, number, boolean, url, email, json, array, date, or enum array)
pattern: Regular
expression for pattern matchingdefault: Default value
if variable is missing or emptydescription:
Human-readable descriptionerror: Custom error
handler functionrequired: Whether the
variable is required (default: true)const env = loadEnv(schema);
console.log(env.SECRET_TOKEN); // "MySuperSecretToken12345678901234567890"
console.log(env.LOG_LEVEL); // "debug" or "info" (default)
console.log(env.API_VERSION); // "v2.1.0"
SECRET_TOKEN=short →
Throws error (doesn't match pattern)loadEnv function accepts
an optional second parameter with configuration options:
const env = loadEnv(schema, {
path: ".env", // Path to .env file (default: ".env")
strict: true, // Warn about unknown variables (default: false)
example: true, // Generate .env.example file (default: false)
error: (err) => { // Custom error handler
console.error(err.message);
process.exit(1);
},
debug: true, // Enable debug mode (default: false)
});
| Option | Type | Default | Description |
|---|---|---|---|
path |
string |
".env" |
Path to the environment file |
strict |
boolean |
false |
If true, warns about
variables in .env
that are not in the schema |
example |
boolean |
false |
If true, generates a
.env.example file
with all schema keys |
error |
(error: Error) =>
void |
undefined |
Custom error handler function |
debug |
boolean |
false |
Enable debug logging |
error
callback:
// Method 1: Try-catch
try {
const env = loadEnv(schema);
} catch (error) {
console.error("Validation failed:", error.message);
process.exit(1);
}
// Method 2: Error callback
const env = loadEnv(schema, {
error: (err) => {
console.error("Validation failed:", err.message);
process.exit(1);
},
});
[EnvGuard] Missing env
variable: PORT - Required variable is missing[EnvGuard] PORT must be a
number - Type validation failed[EnvGuard] Invalid value for
NODE_ENV: staging, allowed: development, production, test -
Enum validation failed[EnvGuard] Failed to parse .env
file at /path/to/.env: ... - File parsing errorconst schema = {
SECRET_TOKEN: "string",
API_KEY: "string",
DATABASE_PASSWORD: "string",
};
const env = loadEnv(schema);
// .env
// SECRET_TOKEN=my-secret
// API_KEY=my-key
// DATABASE_PASSWORD=my-password
console.log(env.SECRET_TOKEN); // "[HIDDEN]"
console.log(env.API_KEY); // "[HIDDEN]"
console.log(env.DATABASE_PASSWORD); // "[HIDDEN]"
.env.example file:
const env = loadEnv(schema, {
example: true,
});
.env.example
file with all schema keys (without values):
DATABASE_URL=
PORT=
DEBUG=
API_BASE_URL=
.env file:
const env = loadEnv(schema, {
strict: true,
});
// If .env contains variables not in schema:
// [EnvGuard] Unknown env variables: UNKNOWN_VAR, ANOTHER_UNKNOWN
import { loadEnv } from '@osmn-byhn/envguard';
import { EnvSchema } from '@osmn-byhn/envguard';
const schema: EnvSchema = {
// Required variables
DATABASE_URL: "string",
PORT: "number",
DEBUG: "boolean",
API_BASE_URL: "url",
ADMIN_EMAIL: "email",
NODE_ENV: ["development", "production", "test"],
// Optional variables
API_KEY: "string?",
TIMEOUT: "number?",
// Complex types
CONFIG: "json",
ALLOWED_ORIGINS: "array",
START_DATE: "date",
// Custom validation
SECRET_TOKEN: {
type: "string",
pattern: /^[A-Za-z0-9]{32,}$/,
required: true,
},
LOG_LEVEL: {
type: ["debug", "info", "warn", "error"],
default: "info",
},
};
const env = loadEnv(schema, {
strict: true,
example: true,
error: (err) => {
console.error("❌ Environment validation failed:", err.message);
process.exit(1);
},
});
// Use validated environment variables
console.log(Server starting on port ${env.PORT});
console.log(Database: ${env.DATABASE_URL});
console.log(Environment: ${env.NODE_ENV});
import { loadEnv, EnvSchema, ParsedEnv } from '@osmn-byhn/envguard';
const schema: EnvSchema = {
PORT: "number",
DATABASE_URL: "string",
};
const env: ParsedEnv = loadEnv(schema);
// env is fully typed!
?) - For variables that
have sensible defaults or are truly optionalAuthor: Osman Beyhan
❤️ Make via MDtoWeb