scenv-zod
scenv-zod is a utility library that integrates the Zod schema validation library with scenv, a package for managing environment variables and configuration. It provides a `parser` function that allows developers to define robust validation and coercion rules for their configuration variables using Zod schemas. This ensures type safety and data integrity when reading values from environment variables, CLI arguments, or default settings within scenv. Currently at version 0.4.0, it's a relatively new and actively developed package, primarily focused on enhancing `scenv`'s parsing capabilities. It differentiates itself by leveraging Zod's powerful schema definition language for parsing, offering granular control over data types, transformations (e.g., string to number/boolean), and comprehensive error handling. This makes it a strong choice for applications requiring strict and predictable configuration validation, reducing runtime errors caused by malformed environment variables. Its concise API simplifies complex validation logic, promoting cleaner and more maintainable configuration codebases.
Common errors
-
ZodError: Invalid input
cause The value retrieved for a configuration variable (from env, CLI, or default) does not conform to the defined Zod schema.fixInspect the `error.errors` array in the `ZodError` for specific validation issues. Ensure string inputs are correctly coerced (e.g., `z.coerce.number()`) and that all rules (e.g., `min`, `max`, `email`) are met by the provided value. -
Error: Cannot find module 'scenv' or 'zod'
cause The peer dependencies `scenv` or `zod` are not installed in the project, or they are not resolvable.fixInstall the required peer dependencies using your package manager: `npm install scenv zod` or `pnpm add scenv zod`. -
TypeError: Cannot read properties of undefined (reading 'get')
cause The `scenv` function or variable definition was not correctly executed or imported, resulting in an undefined variable object when `.get()` is called.fixVerify that `import { scenv } from 'scenv';` is present and that the `scenv()` function is called with valid arguments, returning a variable object before `.get()` is invoked.
Warnings
- gotcha Environment variables, CLI arguments, and context values are always read as strings by `scenv`. Direct Zod schema validation for non-string types (e.g., `z.number()`, `z.boolean()`) will fail unless proper coercion is applied.
- gotcha The `.get()` method from `scenv` (when using a scenv-zod parser) will throw a `ZodError` if validation fails. This can lead to unhandled promise rejections if not caught.
- breaking Major version updates of `zod` itself may introduce breaking changes to schema definition or validation behavior that could impact existing `scenv-zod` parsers.
Install
-
npm install scenv-zod -
yarn add scenv-zod -
pnpm add scenv-zod
Imports
- parser
const { parser } = require('scenv-zod');import { parser } from 'scenv-zod'; - scenv
const scenv = require('scenv');import { scenv } from 'scenv'; - z
const z = require('zod');import { z } from 'zod';
Quickstart
import { scenv } from "scenv";
import { parser } from "scenv-zod";
import { z } from "zod";
const port = scenv("Port", {
key: "port",
env: "PORT",
default: 3000,
parser: parser(z.coerce.number().min(1).max(65535))
});
const debug = scenv("Debug", {
key: "debug",
env: "DEBUG",
default: false,
parser: parser(
z.union([z.boolean(), z.literal("true"), z.literal("false")])
.transform((v) => v === true || v === "true")
)
});
// Simulate environment variables for demonstration
process.env.PORT = process.env.PORT ?? '8080';
process.env.DEBUG = process.env.DEBUG ?? 'true';
async function runConfig() {
try {
const portNum = await port.get(); // number
const isDebug = await debug.get(); // boolean
console.log(`Application Port: ${portNum} (Type: ${typeof portNum})`);
console.log(`Debug Mode: ${isDebug} (Type: ${typeof isDebug})`);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Validation failed:', error.errors);
} else {
console.error('An unexpected error occurred:', error);
}
}
}
runConfig();