1.5.1 • Published 12 months ago

dotenv-zod-validator v1.5.1

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

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 (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

MethodDescriptionundefinedemptyand error
objectAlias for z.object___
enumAlias for z.enum❌️❌️invalid text
stringAlias for z.string❌️✅️_
numberConverts to a number.❌️❌️invalid number
booleanConverts to a boolean. (TRUE: true, TRUE, 1 / FALSE: other)❌️❌️_

Tests

npm run test

License

MIT License

1.5.1

12 months ago

1.5.0

12 months ago

1.4.0

1 year ago

1.3.0

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.2

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago