Skip to content
rest-rpc
Esc
↑↓navigate↵open⌘Jpreview
On this page

Content Types and Codecs

How requests and responses are encoded, and how to send formats other than JSON.

Params, Query and Headers

The client turns each value into a string, and the server’s schemas receive strings:

const 
const search: HandledRoute<{
    readonly method: "GET";
    readonly path: "/users/:id/posts";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodCoercedNumber<unknown>;
        }, z.core.$strip>];
        query: readonly [z.ZodObject<{
            page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
            tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, string[]>
search
= const route: Omit<ServerRouteBuilder<RootBuilderState, DefaultContext, DefaultContext>, "meta">
Entry point for defining routes with handlers.
@remarksResponses are inferred from the handler unless they are defined before `.handler()`. Routes are runtime-independent: the same route works with the Fetch and Node HTTP handlers.@see{@link https://rest-rpc.vercel.app/docs/quickstart#define-routes}
route
.get<"/users/:id/posts">(path?: "/users/:id/posts" | undefined): Omit<ServerRouteBuilder<WithHttpMethod<RootBuilderState, "GET", "/users/:id/posts">, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithHttpMethod<RootBuilderState, "GET", TPath>>>
Defines a GET route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder}
get
("/users/:id/posts")
.
params<z.ZodObject<{
    id: z.ZodCoercedNumber<unknown>;
}, z.core.$strip>>(schema: z.ZodObject<{
    id: z.ZodCoercedNumber<unknown>;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/users/:id/posts">, "params", z.ZodObject<{
    id: z.ZodCoercedNumber<unknown>;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/users/:id/posts">, "params", TSchema>>>
Defines path parameters.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
params
(import zz.
function object<{
    id: z.ZodCoercedNumber<unknown>;
}>(shape?: {
    id: z.ZodCoercedNumber<unknown>;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    id: z.ZodCoercedNumber<unknown>;
}, z.core.$strip>
object
({ id: z.ZodCoercedNumber<unknown>id: import zz.import coercecoerce.function number<unknown>(params?: string | z.core.$ZodNumberParams): z.ZodCoercedNumber<unknown>number() }))
.
query<z.ZodObject<{
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
}, z.core.$strip>>(schema: z.ZodObject<{
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/users/:id/posts">, "params", z.ZodObject<{
    id: z.ZodCoercedNumber<unknown>;
}, z.core.$strip>>, "query", z.ZodObject<{
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>>
Defines URL query parameters.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
query
(
import zz.
function object<{
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
}>(shape?: {
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
    tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
}, z.core.$strip>
object
({
page: z.ZodOptional<z.ZodCoercedNumber<unknown>>page: import zz.import coercecoerce.function number<unknown>(params?: string | z.core.$ZodNumberParams): z.ZodCoercedNumber<unknown>number().ZodType<any, any, $ZodNumberInternals<unknown>>.optional(): z.ZodOptional<z.ZodCoercedNumber<unknown>>optional(), tags: z.ZodOptional<z.ZodArray<z.ZodString>>tags: import zz.function array<z.ZodString>(element: z.ZodString, params?: string | z.core.$ZodArrayParams): z.ZodArray<z.ZodString>array(import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string()).ZodType<any, any, $ZodArrayInternals<ZodString>>.optional(): z.ZodOptional<z.ZodArray<z.ZodString>>optional(), }), ) .
handler<string[]>(handler: HandlerFor<{
    readonly method: "GET";
    readonly path: "/users/:id/posts";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodCoercedNumber<unknown>;
        }, z.core.$strip>];
        query: readonly [z.ZodObject<{
            page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
            tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, string[]>): HandledRoute<{
    readonly method: "GET";
    readonly path: "/users/:id/posts";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodCoercedNumber<unknown>;
        }, z.core.$strip>];
        query: readonly [z.ZodObject<{
            page: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
            tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, string[]>
Attaches the server handler that completes the route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
handler
(({
params: {
    id: number;
}
params
,
query: {
    page?: number | undefined;
    tags?: string[] | undefined;
}
query
}) => function findPosts(userId: number, query: object): string[]findPosts(
params: {
    id: number;
}
params
.id: numberid,
query: {
    page?: number | undefined;
    tags?: string[] | undefined;
}
query
));
await
const client: {
    search: (request: {
        params: {
            id: unknown;
        };
        query?: {
            page?: unknown;
            tags?: string[] | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: string[];
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
}
client
.
search: (request: {
    params: {
        id: unknown;
    };
    query?: {
        page?: unknown;
        tags?: string[] | undefined;
    } | undefined;
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: string[];
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error>
search
({
params: {
    id: unknown;
}
params
: { id: unknownid: 7 },
query?: {
    page?: unknown;
    tags?: string[] | undefined;
} | undefined
query
: { page?: unknownpage: 2, tags?: string[] | undefinedtags: ["news", "release"] },
}); // GET /users/7/posts?page=2&tags[]=news&tags[]=release
  • Arrays are sent as key[] keys, and only those become arrays. A repeated key without [] keeps its last value.
  • undefined values and empty arrays are left out.
  • Header names are lowercase.

Bodies

A body is JSON unless its content-type header says otherwise. FormData is always sent as multipart/form-data:

const upload = route
	.post("/posts/:id/image")
	.body(z.instanceof(FormData))
	.handler(({ params, body }) => savePostImage(params.id, body.get("image")));

const image = route.get("/posts/:id/image").handler(({ params, respond }) => {
	const image = findPostImage(params.id);
	return respond(image, { headers: { "content-type": image.type } });
});
const form = new FormData();
form.set("image", file);
await client.posts.upload({ params: { id: "post_1" }, body: form });
  • The value doesn’t choose the content type. A Blob returned without a content-type header is sent as JSON.
  • A request body’s content type comes from the call’s content-type header, then the client’s headers, then JSON.
  • A response body’s content type comes from the content-type header set with respond(), then JSON. An async iterable is always a stream, and a returned Response is sent as it is.
  • Errors and streams are always JSON and text/event-stream, whatever codecs say.

Accepted Content Types

A route declares the request content types it accepts in its headers schema:

route
	.post("/posts")
	.headers(z.object({ "content-type": z.literal("text/plain") }))
	.body(z.string())
	.handler(({ body }) => createPost({ title: "Untitled", body }));
  • Without one, a route accepts application/json and multipart/form-data, and answers anything else with UNSUPPORTED_MEDIA_TYPE (415).
  • The schema sees the media type without parameters, such as multipart/form-data without its boundary.
  • A request without a content-type has no body. The rest-rpc client sets it for you, but other clients have to: curl -d sends application/x-www-form-urlencoded.

What the Client Receives

The client’s types are the schema’s output, or the handler’s return type, but the value went through JSON on the way:

const get = route
	.get("/posts/:id")
	.handler(() => ({ title: "Hello", publishedAt: new Date() }));

const { body } = await client.posts.get({ params: { id: "1" } });
body.publishedAt; // typed as Date, but the string "2026-11-17T12:00:00.000Z"

Custom Codecs

A codec encodes and decodes bodies of a content type. Pass the same codecs to the server and the client in bodyCodecs. This one keeps Date and other types with superjson:

import { bodyCodec, createClient } from "@rest-rpc/core";
import { createApp, route } from "@rest-rpc/server";
import superjson from "superjson";

const superjsonCodec = bodyCodec("application/vnd.superjson+json", {
	serialize: (value) => superjson.stringify(value),
	deserialize: async (body) => superjson.parse(await body.text()),
});

// Sends every response of routes built from it as superjson
const superjsonRoute = route.use(async ({ next }) => {
	const response = await next();
	return {
		...response,
		headers: {
			...response.headers,
			"content-type": "application/vnd.superjson+json",
		},
	};
});

createApp(router, { bodyCodecs: [superjsonCodec] });
const client = createClient(getContract(), { bodyCodecs: [superjsonCodec] });
function bodyCodec(
	/** A media type, a pattern such as `/\+json$/`, or a list. */
	mediaTypes: string | RegExp | readonly (string | RegExp)[],
	/** At least one of the two. */
	operations: {
		/**
		 * Returns a string, bytes, `Blob`, `FormData`, `URLSearchParams` or a
		 * stream, or a promise of one. Receives the headers sent with the body.
		 */
		serialize?: (value: unknown, headers: Record<string, string>) => BodyValue;
		/**
		 * Reads the body with Fetch body methods such as `text()`, and returns
		 * the value the schema validates. Receives the headers as received.
		 */
		deserialize?: (
			body: IncomingBody,
			headers: Record<string, string>,
		) => unknown;
	},
): BodyCodec;
  • A custom codec is chosen before the built-in ones for every media type it matches. An exact string match wins over a pattern.
  • serialize and deserialize are chosen separately, so a codec with only one leaves the other to the built-in codec.
  • A body deserialize fails on is answered with MALFORMED_REQUEST_BODY (400).
  • To receive request bodies in the format, declare its content type in the route’s headers schema.

Codec Headers

A codec receives the headers sent with a body, and can add its own with serializedBody(). This one marks a Uint8Array so it arrives as one instead of a Blob:

import { binaryCodec, bodyCodec, serializedBody } from "@rest-rpc/core";

const bytes = bodyCodec("application/octet-stream", {
	serialize: (value) =>
		value instanceof Uint8Array
			? serializedBody(value, { headers: { "x-body": "uint8array" } })
			: binaryCodec.serialize(value),
	deserialize: async (body, headers) =>
		headers["x-body"] === "uint8array"
			? new Uint8Array(await body.arrayBuffer())
			: binaryCodec.deserialize(body),
});
  • Headers a codec returns replace those of the same name set by a handler or call.
  • Browsers hide custom response headers from cross-origin requests unless the server lists them in Access-Control-Expose-Headers.

Built-in Codecs

The built-in codecs are exported, so a custom codec can fall back to them:

/** `application/json` and `*+json`. */
const jsonCodec: BodyCodec;
/** `application/x-www-form-urlencoded`, as `URLSearchParams`. */
const urlEncodedCodec: BodyCodec;
/** `multipart/form-data`, as `FormData`. */
const formDataCodec: BodyCodec;
/** `text/*`, as a string. */
const textCodec: BodyCodec;
/** Every other media type. Sends bytes, a `Blob` or a stream, and receives a `Blob`. */
const binaryCodec: BodyCodec;

A built-in codec throws a BodySerializationError for a value it can’t encode, such as an object sent as image/png. The server throws it after the handler runs, and the client before the request is sent:

class BodySerializationError extends TypeError {
	/** The media type the value was serialized for. */
	readonly mediaType: string | undefined;
	/** The kinds of values the codec encodes, such as `["FormData"]`. */
	readonly expected: readonly string[];
	/** The kind of value received, such as `"Object"`. */
	readonly received: string;
}

Was this page helpful?