scenv-zod

0.4.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates defining environment variables with Zod validation, coercing strings to numbers and booleans, and handling potential errors during parsing using `scenv` and `scenv-zod`.

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

view raw JSON →