Validated Type-Safe HTTP Requests with Zod
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
-
ReferenceError: z is not defined
cause The Zod library, `zod`, is not installed or imported.fixEnsure `npm install zod` is run and `import { z } from 'zod';` is present in your file. -
TypeError: (0 , zod_request__WEBPACK_IMPORTED_MODULE_0__.fetch) is not a function
cause Attempting to use `zod-request` with CommonJS `require()` syntax in an ESM-only environment, or a misconfigured bundler.fixEnsure your project uses ESM imports (`import { fetch } from 'zod-request';`) and your `package.json` specifies `"type": "module"` if running directly in Node.js, or configure your bundler (Webpack/Rollup/Vite) correctly. -
ZodError: Invalid input
cause The incoming HTTP response body or outgoing request body does not match the defined Zod schema.fixInspect the actual payload using network tools or `console.error(error)` in the catch block to debug schema discrepancies. Adjust your Zod schema to accurately reflect the data structure. -
TypeError: fetch is not a function
cause The native `fetch` API is not available in the current environment (e.g., older Node.js versions) or the `zod-request` `fetch` was not correctly imported.fixEnsure your Node.js version is >=18.0.0. Verify `import { fetch } from 'zod-request';` is at the top of your file.
Warnings
- gotcha zod-request requires `zod` as a peer dependency for schema definition. Forgetting to install it will lead to runtime errors.
- gotcha As a relatively new library (v0.2.2), `zod-request`'s API surface might evolve rapidly. Monitor release notes for potential breaking changes in minor versions.
- gotcha Response body validation only occurs when methods like `response.json()` or `response.formData()` are called. Using `response.unsafeJson()` bypasses Zod validation entirely.
- gotcha Incorrectly defining `schema.body` for request payloads or `schema.response` for response payloads will lead to validation failures or unexpected type inference.
Install
-
npm install zod-request -
yarn add zod-request -
pnpm add zod-request
Imports
- fetch
const { fetch } = require('zod-request')import { fetch } from 'zod-request' - Response
import type { Response } from 'zod-request' - RequestInit
import type { RequestInit } from 'zod-request'
Quickstart
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();