Validated Type-Safe HTTP Requests with Zod

0.2.2 · active · verified Wed Apr 22

zod-request (version 0.2.2) is a JavaScript/TypeScript library designed to provide validated and type-safe HTTP requests by integrating with the Zod schema validation library. It offers an API that closely mirrors the native `fetch` function, enhancing it with automatic request and response payload validation against Zod schemas. This ensures that both outgoing request bodies and incoming response data conform to predefined types, significantly reducing runtime errors related to data shape. The library is environment-agnostic, supporting Node.js (v18+), browsers, and other JavaScript runtimes like Bun. Its key differentiators include its `fetch`-like interface for familiarity, universal compatibility, and its deep integration with Zod, allowing developers to leverage Zod's powerful schema definition capabilities for end-to-end type safety in network communication. As of its current version, 0.2.2, it appears to be in an active development phase, with a focus on core features and stability rather than a fixed release cadence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to fetch and validate an array of to-do items from a public API using Zod schemas for response validation.

import { fetch } from 'zod-request';
import { z } from 'zod';

const todoSchema = z.object({
  userId: z.number(),
  id: z.number(),
  title: z.string(),
  completed: z.boolean()
});

async function fetchTodos() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      schema: {
        response: z.array(todoSchema)
      }
    });

    const data = await response.json();
    console.log('Fetched data length:', data.length);
    console.log('First item:', data[0]);
    // Example of accessing data safely, TypeScript will infer the type based on todoSchema
    if (data.length > 0) {
      console.log('First todo title:', data[0].title);
    }
  } catch (error) {
    console.error('Error fetching todos:', error);
  }
}

fetchTodos();

view raw JSON →