---
title: Content Types and Codecs
description: 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:

```ts twoslash
import { createClient } from "@rest-rpc/core";
import { route } from "@rest-rpc/server";
import * as z from "zod";
declare function findPosts(userId: number, query: object): string[];
// ---cut---
const search = route
	.get("/users/:id/posts")
	.params(z.object({ id: z.coerce.number() }))
	.query(
		z.object({
			page: z.coerce.number().optional(),
			tags: z.array(z.string()).optional(),
		}),
	)
	.handler(({ params, query }) => findPosts(params.id, query));
// ---cut-start---
const client = createClient({ search }, { origin: "http://localhost" });
// ---cut-end---

await client.search({
	params: { id: 7 },
	query: { page: 2, tags: ["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.

:::warning[Values are sent with `String()`]

- A `Date` becomes a local time string, not ISO. Send `toISOString()`.
- An object becomes `"[object Object]"`. Send its fields as separate keys.
- Booleans become `"true"` and `"false"`. Read them with `z.stringbool()`:
  `z.coerce.boolean()` reads `"false"` as `true`.
  :::

## Bodies

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

```ts
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 } });
});
```

```ts
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](/docs/errors) and [streams](/docs/server-sent-events) 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:

```ts
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:

```ts
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"
```

:::warning

- Use schemas whose output is what JSON sends, such as `z.iso.datetime()`,
  or a [codec](#custom-codecs) that keeps the types.
- Type binary bodies as `Blob`, which is what they arrive as.
- Bodies are read whole before the call resolves. To stream a large body, use
  a codec whose `deserialize` returns `body.body`.
  :::

## 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](https://www.npmjs.com/package/superjson):

```ts
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] });
```

```ts
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](#accepted-content-types).

### 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`:

```ts
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:

```ts
/** `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:

```ts
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;
}
```
