{"id":17413,"library":"zod-request","title":"Validated Type-Safe HTTP Requests with Zod","description":"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.","status":"active","version":"0.2.2","language":"javascript","source_language":"en","source_url":"git://github.com/shahradelahi/zod-request","tags":["javascript","zod","request","http","fetch","browser","node","type-safe","typescript"],"install":[{"cmd":"npm install zod-request","lang":"bash","label":"npm"},{"cmd":"yarn add zod-request","lang":"bash","label":"yarn"},{"cmd":"pnpm add zod-request","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for defining schemas to validate request and response payloads.","package":"zod","optional":false}],"imports":[{"note":"The primary enhanced fetch function, providing Zod validation. zod-request is primarily an ESM library, though bundlers can transpile for CJS.","wrong":"const { fetch } = require('zod-request')","symbol":"fetch","correct":"import { fetch } from 'zod-request'"},{"note":"Type import for the enhanced Response object returned by `zod-request`'s fetch, useful for explicit type annotations.","symbol":"Response","correct":"import type { Response } from 'zod-request'"},{"note":"Type import for the extended RequestInit options, which includes the `schema` property for defining Zod validation schemas.","symbol":"RequestInit","correct":"import type { RequestInit } from 'zod-request'"}],"quickstart":{"code":"import { fetch } from 'zod-request';\nimport { z } from 'zod';\n\nconst todoSchema = z.object({\n  userId: z.number(),\n  id: z.number(),\n  title: z.string(),\n  completed: z.boolean()\n});\n\nasync function fetchTodos() {\n  try {\n    const response = await fetch('https://jsonplaceholder.typicode.com/todos', {\n      method: 'GET',\n      headers: {\n        'Content-Type': 'application/json'\n      },\n      schema: {\n        response: z.array(todoSchema)\n      }\n    });\n\n    const data = await response.json();\n    console.log('Fetched data length:', data.length);\n    console.log('First item:', data[0]);\n    // Example of accessing data safely, TypeScript will infer the type based on todoSchema\n    if (data.length > 0) {\n      console.log('First todo title:', data[0].title);\n    }\n  } catch (error) {\n    console.error('Error fetching todos:', error);\n  }\n}\n\nfetchTodos();","lang":"typescript","description":"Demonstrates how to fetch and validate an array of to-do items from a public API using Zod schemas for response validation."},"warnings":[{"fix":"npm install zod","message":"zod-request requires `zod` as a peer dependency for schema definition. Forgetting to install it will lead to runtime errors.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"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.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"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.","message":"Response body validation only occurs when methods like `response.json()` or `response.formData()` are called. Using `response.unsafeJson()` bypasses Zod validation entirely.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"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.","message":"Incorrectly defining `schema.body` for request payloads or `schema.response` for response payloads will lead to validation failures or unexpected type inference.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `npm install zod` is run and `import { z } from 'zod';` is present in your file.","cause":"The Zod library, `zod`, is not installed or imported.","error":"ReferenceError: z is not defined"},{"fix":"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.","cause":"Attempting to use `zod-request` with CommonJS `require()` syntax in an ESM-only environment, or a misconfigured bundler.","error":"TypeError: (0 , zod_request__WEBPACK_IMPORTED_MODULE_0__.fetch) is not a function"},{"fix":"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.","cause":"The incoming HTTP response body or outgoing request body does not match the defined Zod schema.","error":"ZodError: Invalid input"},{"fix":"Ensure your Node.js version is >=18.0.0. Verify `import { fetch } from 'zod-request';` is at the top of your file.","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.","error":"TypeError: fetch is not a function"}],"ecosystem":"npm","meta_description":null}