@ameykhoje/env-guard
v1.1.2
Published
Type-safe environment validation library
Maintainers
Readme
@ameykhoje/env-guard
Type-safe environment variable validation for JavaScript and TypeScript.
Validate, transform and safely access environment variables with support for:
- String validation
- Number validation
- Enum validation
- Boolean parsing
- Arrays
- Optional values
- Defaults
- Custom validators
- Partial success with collected errors
- End-to-end TypeScript inference
Installation
npm install @ameykhoje/env-guardor
yarn add @ameykhoje/env-guardQuick Start
import {
env,
string,
number,
} from "@ameykhoje/env-guard";
const config = env(
{
VITE_API_URL:
string()
.url()
.compile(),
VITE_PORT:
number()
.min(1000)
.max(9999)
.compile(),
},
import.meta.env,
);
console.log(config.success);
console.log(config.data);Result:
{
success: true,
data: {
VITE_API_URL:
"https://api.com",
VITE_PORT:
3000
},
errors: []
}Parsing Result
env() never crashes automatically.
const result =
env(schema);
if (!result.success) {
console.log(
result.errors,
);
}
console.log(
result.data,
);Force strict mode:
const config =
result.unwrap();Throws when validation fails.
String Builder
string()
.minLength(4)
.regex(/abc/)
.email()
.url()
.uuid()
.optional()
.default("value")
.compile()Example:
USERNAME:
string()
.minLength(3)
.compile()Number Builder
number()
.min(1)
.max(100)
.optional()
.default(10)
.compile()Example
PORT:
number()
.min(1000)
.max(9999)
.compile()Boolean Builder
boolean()
.default(false)
.optional()
.compile()Supports:
DEBUG=true
DEBUG=false
DEBUG=1
DEBUG=0Array Builder
array(
number()
.min(5)
.compile(),
)
.compile()Environment:
PORTS=10,20,30Result:
[10,20,30]Nested validation supported:
array(
number()
.min(5)
.max(100)
.compile(),
)Optional Values
TOKEN:
string()
.optional()
.compile()Missing value:
TOKEN === undefinedDefaults
HOST:
string()
.default(
"localhost",
)
.compile()Missing value:
HOST === "localhost"Custom Validation
string()
.custom(
value =>
value.startsWith(
"sk_",
),
"Invalid API key",
)
.compile()Email Validation
EMAIL:
string()
.email()
.compile()UUID Validation
ID:
string()
.uuid()
.compile()Result Shape
Success:
{
success: true,
data: { ... },
errors: []
}Failure:
{
success: false,
data: {
partial:
"values"
},
errors: [
{
key:
"PORT",
message:
"Minimum acceptable only 1000",
received:
500
}
]
}Example With Vite
.env
VITE_API_URL=https://api.com
VITE_PORT=3000Usage:
const config =
env(
{
VITE_API_URL:
string()
.url()
.compile(),
VITE_PORT:
number()
.compile(),
},
import.meta.env,
);Example With Node.js
const config =
env(
schema,
process.env,
);Upcoming Features
- Number Validation - Posivite, Negative, Finite
- Array - Unique Elements, Non Empty, Length
- Date(new)
- Transformation (new)
- Built-in dotenv loading
- Multiple env support
- Prefix validation. Eg. VITE_, NEXT_PUBLIC_
- Asynchronous validations
- Generate .env.example
License
MIT
