Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Request validator

Validated

Validate request bodies, query strings, and route params with Zod before your handler runs.

The request validator parses body, query, and params with Zod. It replaces the request values with the parsed result, applies defaults and coercion, and rejects invalid input before your route runs.

The block has no root index.ts. Import adapters from adapters/ and the shared types from contract.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add request-validator
import express from "express";
import { z } from "zod";
import { expressValidator } from "@/blocks/request-validator/adapters/express";

const app = express();
app.use(express.json());

const validateUser = expressValidator({
  body: z.object({
    email: z.string().email()
  })
});

app.post("/users", validateUser, (req, res) => {
  const { body } = validateUser.validated(req);
  res.json({ email: body.email });
});

Register express.json() before the validator. Without a body parser, req.body is undefined and the schema fails.

Files

request-validator/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── core.ts
└── contract.ts

Installation

pnpm dlx blockend-cli add request-validator

The CLI copies core.ts, contract.ts, and one adapter. It installs Zod.

Copy core.ts, contract.ts, and the adapter you need into blocks/request-validator. Install Zod.

Core

import { z } from "zod";
/**
 * Validates arbitrary data against a Zod schema.
 *
 * Returns the parsed data when validation succeeds.
 * Throws a ValidationError when validation fails.
 */
export function coreValidator<TSchema extends z.ZodTypeAny>(
  schema: TSchema,
  data: unknown
): z.infer<TSchema> {
  return schema.parse(data);
}

Contract

import { z } from "zod";

/**
 * Schemas for the different parts of an incoming HTTP request.
 *
 * The generic parameters preserve the concrete Zod schema types so
 * adapters can infer the validated data instead of falling back to
 * `unknown`.
 */
export interface RequestValidationSchema<
  TBody extends z.ZodTypeAny = z.ZodTypeAny,
  TQuery extends z.ZodTypeAny = z.ZodTypeAny,
  TParams extends z.ZodTypeAny = z.ZodTypeAny
> {
  body?: TBody;
  query?: TQuery;
  params?: TParams;
}

Express adapter

import type { Request, Response, NextFunction, RequestHandler } from "express";
import { z, ZodError } from "zod";
import { coreValidator } from "../core.js";
import type { RequestValidationSchema } from "../contract.js";

/**
 * Controls how validation failures are handled.
 */
type ExpressValidatorOptions = {
  /**
   * When `true`, validation errors are forwarded to Express via `next(error)`
   * so they can be handled by a global error handler.
   *
   * When `false` (default), this middleware immediately returns a
   * `400 Bad Request` response using its built-in JSON format.
   */
  propagateErrors?: boolean;
};

/**
 * Internal symbol used to store the validated request payload on the request.
 *
 * Using a Symbol avoids collisions with application-defined request properties.
 */
export const VALIDATED_KEY = Symbol("blockend.validated");

/**
 * The validated and parsed request data.
 *
 * Values are already transformed by Zod (defaults applied, coercion performed,
 * transforms executed, etc.).
 */
type ValidatedData<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> = {
  body: z.infer<TBody>;
  query: z.infer<TQuery>;
  params: z.infer<TParams>;
};

/**
 * Custom request type that carries the validated payload.
 */
interface ValidatedRequest<
  TBody extends z.ZodTypeAny = z.ZodTypeAny,
  TQuery extends z.ZodTypeAny = z.ZodTypeAny,
  TParams extends z.ZodTypeAny = z.ZodTypeAny
> extends Request {
  [VALIDATED_KEY]?: ValidatedData<TBody, TQuery, TParams>;
}

/**
 * Express middleware augmented with a helper for retrieving the fully typed,
 * validated request data.
 */
type ValidatorMiddleware<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> = RequestHandler & {
  /**
   * Returns the validated request payload.
   *
   * Throws if the middleware has not yet executed for the current request.
   */
  validated: (req: Request) => ValidatedData<TBody, TQuery, TParams>;
};

/**
 * Creates Express middleware that validates the request body, query string,
 * and route parameters using Zod schemas.
 *
 * On success:
 * - Request values are parsed using Zod.
 * - Default values, coercion, and transforms are applied.
 * - `req.body`, `req.query`, and `req.params` are replaced with the parsed values.
 * - The typed values are also accessible via `middleware.validated(req)`.
 *
 * On validation failure:
 * - Returns a `400 Bad Request` response by default.
 * - Or forwards the `ZodError` to the next error handler when
 *   `propagateErrors` is enabled.
 */
export function expressValidator<
  TBody extends z.ZodTypeAny = z.ZodTypeAny,
  TQuery extends z.ZodTypeAny = z.ZodTypeAny,
  TParams extends z.ZodTypeAny = z.ZodTypeAny
>(
  schemas: RequestValidationSchema<TBody, TQuery, TParams>,
  options: ExpressValidatorOptions = { propagateErrors: false }
): ValidatorMiddleware<TBody, TQuery, TParams> {
  const middleware: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
    const validatedReq = req as ValidatedRequest<TBody, TQuery, TParams>;

    try {
      const bodySchema = schemas.body ?? z.any();
      const querySchema = schemas.query ?? z.any();
      const paramsSchema = schemas.params ?? z.any();

      // Validate each part independently so TypeScript can track the
      // inferred type of each piece without losing it inside z.object().
      const body = coreValidator(bodySchema, req.body);
      const query = coreValidator(querySchema, req.query);
      const params = coreValidator(paramsSchema, req.params);

      req.body = body;

      Object.defineProperty(req, "query", {
        value: query,
        writable: true,
        enumerable: true,
        configurable: true
      });

      Object.defineProperty(req, "params", {
        value: params,
        writable: true,
        enumerable: true,
        configurable: true
      });

      validatedReq[VALIDATED_KEY] = {
        body,
        query,
        params
      };

      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errors = z.flattenError(error).fieldErrors;

        if (options.propagateErrors) {
          next(error);
          return;
        }

        res.status(400).json({
          success: false,
          data: null,
          message: "Validation failed",
          errors
        });

        return;
      }

      next(error);
    }
  };

  (middleware as ValidatorMiddleware<TBody, TQuery, TParams>).validated = (
    req: Request
  ): ValidatedData<TBody, TQuery, TParams> => {
    const validatedReq = req as ValidatedRequest<TBody, TQuery, TParams>;

    const data = validatedReq[VALIDATED_KEY];

    if (!data) {
      throw new Error(
        "[blockend] expressValidator middleware has not run for this request. " +
          "Ensure it is registered before your route handler."
      );
    }

    return data;
  };

  return middleware as ValidatorMiddleware<TBody, TQuery, TParams>;
}

Fastify adapter

import { z, ZodError } from "zod";
import type { FastifyReply, FastifyRequest } from "fastify";

import { coreValidator } from "../core";
import type { RequestValidationSchema } from "../contract";

export interface FastifyValidatorOptions {
  propagateErrors?: boolean;
}

export const VALIDATED_KEY = Symbol("blockend.validated");

type ValidatedData<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> = {
  body: z.infer<TBody>;
  query: z.infer<TQuery>;
  params: z.infer<TParams>;
};

interface ValidatedRequest<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> extends FastifyRequest {
  [VALIDATED_KEY]?: ValidatedData<TBody, TQuery, TParams>;
}

type ValidatorHook<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> = {
  (request: FastifyRequest, reply: FastifyReply): Promise<void>;

  validated(request: FastifyRequest): ValidatedData<TBody, TQuery, TParams>;
};

export function fastifyValidator<
  TBody extends z.ZodTypeAny = z.ZodTypeAny,
  TQuery extends z.ZodTypeAny = z.ZodTypeAny,
  TParams extends z.ZodTypeAny = z.ZodTypeAny
>(
  schemas: RequestValidationSchema<TBody, TQuery, TParams>,
  options: FastifyValidatorOptions = {}
): ValidatorHook<TBody, TQuery, TParams> {
  const hook = async (request: FastifyRequest, reply: FastifyReply) => {
    const validatedReq = request as ValidatedRequest<TBody, TQuery, TParams>;

    try {
      const body = coreValidator(schemas.body ?? z.any(), request.body);

      const query = coreValidator(schemas.query ?? z.any(), request.query);

      const params = coreValidator(schemas.params ?? z.any(), request.params);

      request.body = body;
      request.query = query;
      request.params = params;

      validatedReq[VALIDATED_KEY] = {
        body,
        query,
        params
      };
    } catch (err) {
      if (err instanceof ZodError) {
        if (options.propagateErrors) {
          throw err;
        }

        return reply.status(400).send({
          success: false,
          data: null,
          message: "Validation failed",
          errors: z.flattenError(err).fieldErrors
        });
      }

      throw err;
    }
  };

  hook.validated = (request: FastifyRequest): ValidatedData<TBody, TQuery, TParams> => {
    const validatedReq = request as ValidatedRequest<TBody, TQuery, TParams>;

    const data = validatedReq[VALIDATED_KEY];

    if (!data) {
      throw new Error("[blockend] fastifyValidator has not run for this request.");
    }

    return data;
  };

  return hook as ValidatorHook<TBody, TQuery, TParams>;
}

Hono adapter

import { z, ZodError } from "zod";
import type { Context, MiddlewareHandler } from "hono";

import { coreValidator } from "../core";
import type { RequestValidationSchema } from "../contract";

type HonoValidatorOptions = {
  /**
   * When true, throws the ZodError so Hono's error handler can catch it.
   * Otherwise returns a 400 response.
   */
  propagateErrors?: boolean;
};

export type ValidatedData<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
> = {
  body: z.infer<TBody>;
  query: z.infer<TQuery>;
  params: z.infer<TParams>;
};

const VALIDATED_KEY = "blockend.validated";

export function honoValidator<
  TBody extends z.ZodTypeAny = z.ZodTypeAny,
  TQuery extends z.ZodTypeAny = z.ZodTypeAny,
  TParams extends z.ZodTypeAny = z.ZodTypeAny
>(
  schemas: RequestValidationSchema<TBody, TQuery, TParams>,
  options: HonoValidatorOptions = {}
): MiddlewareHandler {
  return async (c, next) => {
    try {
      const bodySchema = schemas.body ?? z.any();
      const querySchema = schemas.query ?? z.any();
      const paramsSchema = schemas.params ?? z.any();

      const body = coreValidator(bodySchema, await c.req.json().catch(() => undefined));

      const query = coreValidator(
        querySchema,
        Object.fromEntries(new URL(c.req.url).searchParams.entries())
      );

      const params = coreValidator(paramsSchema, c.req.param());

      c.set(VALIDATED_KEY, {
        body,
        query,
        params
      });

      await next();
    } catch (error) {
      if (error instanceof ZodError) {
        if (options.propagateErrors) {
          throw error;
        }

        return c.json(
          {
            success: false,
            data: null,
            message: "Validation failed",
            errors: z.flattenError(error).fieldErrors
          },
          400
        );
      }

      throw error;
    }
  };
}

export function validated<
  TBody extends z.ZodTypeAny,
  TQuery extends z.ZodTypeAny,
  TParams extends z.ZodTypeAny
>(c: Context): ValidatedData<TBody, TQuery, TParams> {
  const data = c.get(VALIDATED_KEY);

  if (!data) {
    throw new Error(
      "[blockend] honoValidator middleware has not run for this request. " +
        "Ensure it is registered before your route handler."
    );
  }

  return data as ValidatedData<TBody, TQuery, TParams>;
}

Configuration

The adapter takes a schema object and an options object:

{
  body?: z.ZodTypeAny;
  query?: z.ZodTypeAny;
  params?: z.ZodTypeAny;
}
{
  propagateErrors?: boolean; // default false
}

Parts you omit are not validated. They are parsed with z.any(), which accepts any value. Hono still reads the body as JSON, so a non-JSON body becomes undefined when body validation is omitted.

OptionDefaultDescription
propagateErrorsfalseSend the ZodError to your error handler instead of returning the built-in 400.

Usage

Express

import { z } from "zod";
import { expressValidator } from "@/blocks/request-validator/adapters/express";

const validator = expressValidator({
  body: z.object({
    name: z.string().min(1),
    email: z.string().email()
  }),
  query: z.object({
    page: z.coerce.number().int().min(1).default(1)
  }),
  params: z.object({
    id: z.string().uuid()
  })
});

app.post("/users/:id", validator, (req, res) => {
  const { body, query, params } = validator.validated(req);
  res.json({ body, query, params });
});

The middleware replaces req.body, req.query, and req.params with parsed values. validator.validated(req) returns the same values with their inferred types.

validated throws if the middleware did not run for the request. Keep the middleware on the route or mount it before the handler.

Fastify

import { z } from "zod";
import { fastifyValidator } from "@/blocks/request-validator/adapters/fastify";

const validator = fastifyValidator({
  body: z.object({
    name: z.string(),
    age: z.coerce.number()
  })
});

app.post("/users", { preHandler: validator }, async (request) => {
  const { body } = validator.validated(request);
  return body;
});

Hono

import { Hono } from "hono";
import { z } from "zod";
import { honoValidator, validated } from "@/blocks/request-validator/adapters/hono";

const app = new Hono();

const schema = {
  body: z.object({
    name: z.string()
  })
};

app.post("/users", honoValidator(schema), (c) => {
  const { body } = validated<typeof schema.body, z.ZodTypeAny, z.ZodTypeAny>(c);
  return c.json(body);
});

Hono does not attach a validated method to the middleware. Use the exported validated(c) helper. The generic arguments are optional, but without them the result is not strongly typed.

Error responses

With propagateErrors: false, a Zod failure returns status 400:

{
  "success": false,
  "data": null,
  "message": "Validation failed",
  "errors": {
    "email": ["Invalid email"]
  }
}

The errors object contains field errors from z.flattenError. Nested schema errors may need your own formatter if you want a different shape.

With propagateErrors: true, the adapter passes the original ZodError to the framework error path. Use the error handler block's classifier to turn it into a 400 response:

import { z, ZodError } from "zod";
import { createErrorBoundary } from "@/blocks/error-handler";
import { createExpressErrorHandler } from "@/blocks/error-handler/adapters/express";

const boundary = createErrorBoundary({
  classifier(error) {
    if (!(error instanceof ZodError)) return null;

    return {
      code: "VALIDATION_FAILED",
      message: "Validation failed",
      statusCode: 400,
      category: "VALIDATION",
      details: z.treeifyError(error)
    };
  }
});

app.use(createExpressErrorHandler(boundary));

Behavior

  • Every schema is parsed with schema.parse, so transforms and defaults run.
  • Validation runs before the route handler. Invalid input never reaches your business logic.
  • Express replaces req.query and req.params with parsed values. Fastify assigns them directly. Hono stores the parsed values in its context.
  • A non-Zod error thrown by a schema or transform is forwarded to the framework error path.
  • The Express and Fastify adapters export VALIDATED_KEY if you need the internal symbol. Most code should use validated().

API reference

expressValidator

function expressValidator(
  schemas: RequestValidationSchema,
  options?: { propagateErrors?: boolean }
): RequestHandler & {
  validated(req: Request): ValidatedData;
};

fastifyValidator

function fastifyValidator(
  schemas: RequestValidationSchema,
  options?: { propagateErrors?: boolean }
): {
  (request: FastifyRequest, reply: FastifyReply): Promise<void>;
  validated(request: FastifyRequest): ValidatedData;
};

honoValidator

function honoValidator(
  schemas: RequestValidationSchema,
  options?: { propagateErrors?: boolean }
): MiddlewareHandler;

validated

function validated<TBody, TQuery, TParams>(c: Context): ValidatedData;

Reads the parsed values stored by honoValidator. Throws if the middleware has not run.

coreValidator

function coreValidator<TSchema extends z.ZodTypeAny>(
  schema: TSchema,
  data: unknown
): z.infer<TSchema>;

A thin wrapper around schema.parse for custom adapters.

Production notes

  • Validate at the edge of the request. Do not repeat the same schema in the route.
  • Keep schemas close to the route or in a shared module that both the route and tests import.
  • Do not use z.any() for fields that affect authorization or billing.
  • Treat parsed values as the source of truth. Avoid reading raw req.body after validation.
  • Zod strips unknown keys by default on object schemas. If you need to reject unknown keys, use .strict().

When not to use it

  • You already use a schema-first framework that validates at the route boundary.
  • You need OpenAPI generation from the same schema. This block does not generate specs.
  • You need validation outside HTTP requests. Use Zod directly.

On this page