withJsonResponse

May 26, 2026 ยท View on GitHub

withJsonResponse(options?)

Wraps a fetch function to automatically parse response bodies as JSON. Optionally validates the parsed JSON against a Standard Schema.

Use a Standard Schema compatible validator such as Zod (v3.24+), Valibot, or ArkType.

Unlike other wrappers, this one returns parsed data instead of a Response, so it should be placed last in a pipeline.

Empty responses are not special-cased. If the response body is empty, including 204, 205, or HEAD responses, this wrapper throws the same SyntaxError as Response.json(). This is intentional: returning null would widen every call site's return type to T | null, forcing unnecessary null-checks. If your endpoint can return empty responses, handle that before this wrapper in the pipeline.

Parameters

  • options (optional)
    • schema (StandardSchemaV1) - A Standard Schema object to validate response JSON against.
    • schemaOptions (StandardSchemaV1Options) - Standard Schema options passed as the second argument to schema['~standard'].validate(). Use schemaOptions.libraryOptions for validator-specific options.

Returns

A function that takes a fetch function and returns a wrapped fetch function that returns the parsed JSON data (or validated data if a schema is provided) instead of a Response.

Errors

Throws a SchemaValidationError if the response JSON does not match the provided schema. Throws a SyntaxError if the response body is empty or is not valid JSON.

Example

import {withJsonResponse} from 'fetch-extras';

const fetchJson = withJsonResponse()(fetch);
const data = await fetchJson('/api/user/1');

console.log(data.name);

With schema validation:

import {withJsonResponse} from 'fetch-extras';
import {z} from 'zod';

const userSchema = z.object({name: z.string(), age: z.number()});

const fetchUser = withJsonResponse({schema: userSchema})(fetch);
const user = await fetchUser('/api/user/1');

console.log(user.name);

With Standard Schema options:

import {withJsonResponse} from 'fetch-extras';
import {z} from 'zod';

const fetchUser = withJsonResponse({
	schema: z.object({name: z.string()}),
	schemaOptions: {
		libraryOptions: {
			// Validator-specific Standard Schema options.
		},
	},
})(fetch);

const user = await fetchUser('/api/user/1');

console.log(user.name);

Can be combined with other with* functions (place last in documented pipeline() order):

import {pipeline, withHttpError, withTimeout, withJsonResponse} from 'fetch-extras';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

const fetchUser = pipeline(
	fetch,
	withTimeout(5000),
	withHttpError(),
	withJsonResponse({schema: userSchema}),
);

const user = await fetchUser('/api/user/1');