Skip to content

A very lightweight library for validating and transforming environment variables using Zod.

License

Notifications You must be signed in to change notification settings

tuki0918/dotenv-zod-validator

Repository files navigation

dotenv-zod-validator

dotenv-zod-validator is a very lightweight library for validating and transforming environment variables using Zod.

Installation

npm install dotenv-zod-validator

Usage

.env

NODE_ENV="development"
PORT="3000"
BOOLEAN_FLAG="true"

code

import { zenv } from "dotenv-zod-validator";

const schema = zenv.object({
    NODE_ENV: zenv.enum(["development", "production", "test"]),
    PORT: zenv.number(),
    OPTIONAL_VAR: zenv.string().optional(),
    BOOLEAN_FLAG: zenv.boolean(),
});

const ENV = zenv.validate(schema);
// NODE_ENV: "development"
// PORT: 3000
// BOOLEAN_FLAG: true

// Cannot assign to 'NODE_ENV' because it is a read-only property.
// ENV.NODE_ENV = "production"
Next.js

file: 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,
});

file: 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));

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 test

License

MIT License

About

A very lightweight library for validating and transforming environment variables using Zod.

Resources

License

Stars

Watchers

Forks

Packages

No packages published