npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@schafevormfenster/ts-rest-zod-handler

v0.1.6

Published

Framework-neutral TsRest Zod validation handler with reusable helper utilities

Readme

@schafevormfenster/ts-rest-zod-handler

Framework-neutral TsRest Zod validation handler with reusable helper utilities

npm version License

Purpose

@schafevormfenster/ts-rest-zod-handler is a framework-neutral validation error handler for ts-rest applications. It handles all types of validation errors (JSON parsing, Zod validation, ts-rest request/response validation) and returns consistent error responses while leaving logging responsibilities to client applications.

This package leverages zod-validation-error for user-friendly Zod error message formatting.

Key Features

  • Centralized Error Handler: Single handleZodError function handles all validation scenarios
  • User-Friendly Messages: Uses zod-validation-error for readable error messages
  • Helper Utilities: Reusable functions for custom error workflows (getSafePayloadExcerpt, etc.)
  • Framework-Neutral: No built-in logging - integrate with any logging framework
  • Type-Safe: Returns properly formatted TsRestResponse with ApiError body

Installation

pnpm add @schafevormfenster/ts-rest-zod-handler

Basic Usage

As Error Handler in createNextHandler

The recommended way to use this package:

import { createNextHandler } from "@ts-rest/next";
import { handleZodError } from "@schafevormfenster/ts-rest-zod-handler";
import { MyContract } from "./my.contract";

const handler = createNextHandler(
  MyContract,
  {
    myEndpoint: async ({ body }) => {
      // Your route implementation
      const result = await processData(body);
      
      return {
        status: 200,
        body: {
          status: 200,
          timestamp: new Date().toISOString(),
          data: result,
        },
      };
    },
  },
  {
    jsonQuery: true,
    responseValidation: true,
    handlerType: "app-router",
    errorHandler: handleZodError, // Handles all validation errors
  }
);

export { handler as POST };

Logging Validation Errors

Intercept the response to log validation errors:

export async function POST(request: Request) {
  const response = await handler(request);
  
  // Log validation errors
  if (response.status === 400) {
    const body = await response.clone().json();
    log.error({ error: body.error, method: request.method }, "Validation error");
  }
  
  return response;
}

Using Helper Functions

import {
  getSafePayloadExcerpt,
  isResponseValidationError,
} from "@schafevormfenster/ts-rest-zod-handler";

// For advanced Zod error formatting, use zod-validation-error directly:
import { fromZodError } from "zod-validation-error";
import { ZodError } from "zod";

try {
  schema.parse(data);
} catch (error) {
  if (error instanceof ZodError) {
    const validationError = fromZodError(error as never, {
      maxIssuesInMessage: 3,
      prefix: "Validation error",
    });
    console.log(validationError.message);
    // "Validation error: Expected string, received number at "field.name""
  }
}

// Safely truncate payloads for logging
const excerpt = getSafePayloadExcerpt(largePayload); // Truncated to 500 chars

// Check if error is response validation
if (isResponseValidationError(error)) {
  log.error({ error }, "Response validation failed");
}

Documentation

For detailed usage, integration patterns, and best practices, see:

Exported Functions

Main Handler

  • handleZodError(error: unknown): Promise<TsRestResponse> - Handles all validation errors

Helper Functions

  • getSafePayloadExcerpt(payload: unknown): string | undefined - Safely truncate payloads (500 chars)
  • isResponseValidationError(error: unknown): boolean - Check if error is response validation

For advanced error message formatting, use zod-validation-error directly.

Error Response Format

All errors return a consistent ApiError format:

{
  status: 400 | 500,
  error: "Human-readable error message",
  trace?: unknown // Error details for debugging
}

Status Codes

  • 400: Client errors (validation, malformed JSON, bad requests)
  • 500: Server errors (response validation, internal errors)

License

See the root LICENSE file for license information.


Built with ❤️ by the Schafe vorm Fenster team