$fetch
Use the low-level fetch function for raw responses or schema-validated data.
$fetch is the lowest-level public API.
It behaves like native fetch when no schema is provided, and validates JSON responses when a Standard Schema is provided.
Raw Response Mode
Call $fetch(input, options) without a schema to receive the native Response.
import { $fetch } from "@zap-studio/fetch";
const response = await $fetch("/api/health");
console.log(response.status);
console.log(response.headers.get("content-type"));Use this mode for headers, status codes, streams, text, blobs, or any response that should not be parsed as JSON by the package.
Validated Mode
Call $fetch(input, schema, options) to parse response.json() and validate the parsed value.
import { $fetch } from "@zap-studio/fetch";
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
const user = await $fetch("/api/users/1", UserSchema);Validation output is inferred from the schema.
The schema validates the response body, not request json or body options.
Request Inputs
The input argument uses the same type as global fetch.
import type { FetchInput } from "@zap-studio/fetch/types";
const input: FetchInput = new URL("https://api.example.com/users/1");const request = new Request("https://api.example.com/users/1", {
headers: {
Authorization: `Bearer ${token}`,
},
});
const user = await $fetch(request, UserSchema);Request Options
$fetch accepts standard RequestInit options plus:
| Option | Purpose |
|---|---|
json | JSON-stringify a request body |
searchParams | Add per-request query params |
throwOnFetchError | Throw FetchError for non-ok responses |
throwOnValidationError | Throw ValidationError for schema validation issues |
Use native body for standard fetch behavior.
Use json for JSON convenience.
await $fetch("/api/users", UserSchema, {
method: "POST",
json: {
name: "Ada",
},
});Here, UserSchema validates the response. The json value is the outgoing request payload.
Query Params
searchParams accepts the same inputs as new URLSearchParams(...).
await $fetch("/api/users", UserListSchema, {
searchParams: {
page: "1",
limit: "20",
},
});Non-throw Validation
Set throwOnValidationError: false to receive the raw Standard Schema result.
const result = await $fetch("/api/users/1", UserSchema, {
throwOnValidationError: false,
});
if (result.issues) {
console.error(result.issues);
} else {
console.log(result.value);
}Last updated on