zod-request
zod-request provides validated and type-safe HTTP requests using Zod. It offers the exact same API as native fetch, with extra validation features.
Installation
npm install zod-request zod
Install using your favorite package manager
pnpm
pnpm add zod-request zod
yarn
yarn add zod-request zod
Usage
Basic Usage
Fetch data and validate the response schema automatically.
import { z } from 'zod';
import { fetch } from 'zod-request';
const todoSchema = z.object({
userId: z.number(),
id: z.number(),
title: z.string(),
completed: z.boolean()
});
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
schema: {
response: todoSchema
}
});
// Fully typed as { userId: number; id: number; title: string; completed: boolean }
const data = await response.json();
Form Data
Send multipart form data with automatic Content-Type headers and type-safe validation.
import { z } from 'zod';
import { fetch } from 'zod-request';
const schema = {
body: z.object({
name: z.string(),
age: z.number()
}),
response: z.object({
form: z.record(z.any())
})
};
const response = await fetch('https://httpbin.org/post', {
method: 'POST',
form: {
name: 'John',
age: 20
},
schema
});
const { form } = await response.json();
Path Parameters
Replace template placeholders in the URL safely.
import { z } from 'zod';
import { fetch } from 'zod-request';
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/{{id}}',
{
path: {
id: 1
},
schema: {
path: z.object({
id: z.number()
})
}
}
);
Headers and Search Params
Validate incoming and outgoing request headers and search queries.
import { z } from 'zod';
import { fetch } from 'zod-request';
const response = await fetch('https://api.example.com/search', {
params: {
query: 'zod'
},
headers: {
'X-Api-Key': 'secret'
},
schema: {
searchParams: z.object({
query: z.string()
}),
headers: z.object({
'X-Api-Key': z.string()
})
}
});
Skip Validation
Skip validation and parse raw json or text.
import { fetch } from 'zod-request';
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const rawData = await response.unsafeJson();
Refining Requests
Modify request configuration or rewrite the final URL right before execution.
import { fetch } from 'zod-request';
const response = await fetch('https://api.example.com/data', {
refine: (url, input) => {
input.headers = {
...input.headers,
'X-Request-Id': '12345'
};
return { url, input };
}
});
Custom Global Fetch
Override the default fetch client with any compliant environment fetcher.
import undici from 'undici';
import { setGlobalFetch } from 'zod-request';
setGlobalFetch(undici.fetch);
Documentation
For all configuration options, please see the API docs.
Contributing
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub.
Thanks again for your support, it is much appreciated!
License
MIT Shahrad Elahi and contributors.