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.
npm install zod-requestVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to fetch and validate an array of to-do items from a public API using Zod schemas for response validation.
npm install zod
Always pin to exact versions (e.g., '0.2.2') or use tilde (e.g., '~0.2.2') for minor updates, and review changelogs before upgrading.
Always use `response.json()`, `response.text()`, etc., when validation is desired. Only use `response.unsafeJson()` if you explicitly want to skip validation for that response.
Ensure `schema.body` matches the expected request payload type and `schema.response` accurately describes the expected response body structure, using appropriate Zod methods like `z.object`, `z.array`, `z.string`, etc.
Ensure `npm install zod` is run and `import { z } from 'zod';` is present in your file.Ensure 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.Inspect 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.
Ensure your Node.js version is >=18.0.0. Verify `import { fetch } from 'zod-request';` is at the top of your file.