1.5.1 • Published 11 months ago
dotenv-zod-validator v1.5.1
dotenv-zod-validator
dotenv-zod-validator is a very lightweight library for validating and transforming environment variables using Zod.
Installation
npm install dotenv-zod-validatorUsage (Node)
.env
NODE_ENV="development"
PORT="3000"
BOOLEAN_FLAG="true"
__OTHER__="__other__"code
import { zenv } from "dotenv-zod-validator";
const schema = zenv.object({
NODE_ENV: zenv.enum(["development", "production", "test"]),
PORT: zenv.number(),
BOOLEAN_FLAG: zenv.boolean(),
OPTIONAL_VAR: zenv.string().optional(),
});
const ENV = zenv.validate(schema);
// NODE_ENV: "development"
// PORT: 3000
// BOOLEAN_FLAG: true
// OPTIONAL_VAR: undefined
// Cannot assign to 'NODE_ENV' because it is a read-only property.
// ENV.NODE_ENV = "production"Usage (Next.js)
.env
NEXT_PUBLIC_MY_VALUE="abc"
MY_SECRET="xyz"utils/dotenv.public.ts
import { zenv } from "dotenv-zod-validator";
export const schema = zenv.object({
NEXT_PUBLIC_MY_VALUE: zenv.string(),
});
export const ENV = zenv.validate(schema, {
NEXT_PUBLIC_MY_VALUE: process.env.NEXT_PUBLIC_MY_VALUE,
});
// NEXT_PUBLIC_MY_VALUE: "abc"utils/dotenv.ts
import { zenv } from "dotenv-zod-validator";
import { schema as publicSchema } from "@/utils/dotenv.public";
const schema = zenv.object({
MY_SECRET: zenv.string(),
});
export const ENV = zenv.validate(publicSchema.merge(schema));
// NEXT_PUBLIC_MY_VALUE: "abc"
// MY_SECRET: "xyz"(optional) instrumentation.ts
You can enforce environment variable checks when starting the Next.js server.
import "@/utils/dotenv";Custom Helpers
| Method | Description | undefined | empty | and error |
|---|---|---|---|---|
| object | Alias for z.object | _ | _ | _ |
| enum | Alias for z.enum | ❌️ | ❌️ | invalid text |
| string | Alias for z.string | ❌️ | ✅️ | _ |
| number | Converts to a number. | ❌️ | ❌️ | invalid number |
| boolean | Converts to a boolean. (TRUE: true, TRUE, 1 / FALSE: other) | ❌️ | ❌️ | _ |
Tests
npm run testLicense
MIT License