Server Core

Validation

Type-safe request validation with Zod

Validation with Zod

BlizzardTS integrates seamlessly with Zod to provide robust, type-safe request validation. This ensures that the data entering your application is exactly what you expect, preventing runtime errors and security vulnerabilities.

Installation

Since v0.1.5, zod is a peer dependency. You need to install it in your project:

bun add zod

Usage

Import zValidator from blizzardts and z from zod.

import { zValidator } from "blizzardts";
import { z } from "zod";

Validating JSON Body

Use zValidator("json", schema) to validate the request body.

const userSchema = z.object({
  username: z.string().min(3),
  email: z.string().email(),
  age: z.number().min(18)
});

app.post("/register", zValidator("json", userSchema), (c) => {
  // Access validated data
  // Note: You might need to cast c.req as any for now, or use the generic helper
  const data = (c.req as any).valid.json; 
  
  return c.json({ 
    message: "User registered successfully", 
    user: data 
  });
});

If the validation fails, BlizzardTS automatically returns a 400 Bad Request response with detailed error messages.

Validating Query Parameters

Use zValidator("query", schema) to validate URL query parameters.

const searchSchema = z.object({
  q: z.string(),
  page: z.string().transform(Number).default("1"), // Query params are strings by default
  limit: z.string().transform(Number).default("10")
});

app.get("/search", zValidator("query", searchSchema), (c) => {
  const { q, page, limit } = (c.req as any).valid.query;
  
  return c.json({ 
    results: [], 
    meta: { page, limit, q } 
  });
});

Validating Route Parameters

Use zValidator("param", schema) to validate route parameters.

const idSchema = z.object({
  id: z.string().uuid()
});

app.get("/users/:id", zValidator("param", idSchema), (c) => {
  const { id } = (c.req as any).valid.param;
  return c.text(`User ID: ${id}`);
});

Error Handling

When validation fails, zValidator returns a JSON response like this:

{
  "error": "Validation Error",
  "details": [
    {
      "code": "invalid_type",
      "expected": "string",
      "received": "undefined",
      "path": ["username"],
      "message": "Required"
    }
  ]
}

You can customize this behavior by creating your own validator middleware if needed, but the built-in one covers most use cases.