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

Type-safe REST APIs, for developers and agents.

Write a route once, and it's a validated HTTP endpoint, a typed client call, TanStack Query options, an OpenAPI operation and a tool for MCP servers and agent SDKs.

Types connect all of it, so the compiler shows what a change breaks before anything runs. See Type Safety.

One Route, Every Consumer

// POST /posts/create, JSON body, 200 result.
const 
const create: HandledRoute<{
    readonly method: "POST";
    readonly path: undefined;
    request: {
        body: readonly [z.ZodObject<{
            title: z.ZodString;
            body: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, {
    id: string;
    title: string;
    body: string;
}>
create
= 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
.
body<z.ZodObject<{
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>>(schema: z.ZodObject<{
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithBody<RootBuilderState, z.ZodObject<{
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithBody<RootBuilderState, TSchema>>>
Defines the request body. The route accepts the content types its headers declare in `content-type`, or JSON and `multipart/form-data` without one.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
body
(import zz.
function object<{
    title: z.ZodString;
    body: z.ZodString;
}>(shape?: {
    title: z.ZodString;
    body: 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<{
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>
object
({ title: z.ZodStringtitle: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string(), body: z.ZodStringbody: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string() }))
.
handler<{
    id: string;
    title: string;
    body: string;
}>(handler: HandlerFor<{
    readonly method: "POST";
    readonly path: undefined;
    request: {
        body: readonly [z.ZodObject<{
            title: z.ZodString;
            body: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, {
    id: string;
    title: string;
    body: string;
}>): HandledRoute<{
    readonly method: "POST";
    readonly path: undefined;
    request: {
        body: readonly [z.ZodObject<{
            title: z.ZodString;
            body: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, {
    id: string;
    title: string;
    body: string;
}>
Attaches the server handler that completes the route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
handler
(({
body: {
    title: string;
    body: string;
}
body
: { title: stringtitle, body: stringbody } }) =>
function createPost(title: string, body: string): {
    id: string;
    title: string;
    body: string;
}
createPost
(title: stringtitle, body: stringbody));
// GET /posts/:id with params, query, headers, an error, and response headers. const
const get: HandledRoute<{
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        query: readonly [z.ZodObject<{
            preview: z.ZodOptional<z.ZodEnum<{
                true: "true";
                false: "false";
            }>>;
        }, z.core.$strip>];
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
        headers: readonly [z.ZodObject<{
            "x-request-id": z.ZodOptional<z.ZodString>;
        }, z.core.$strip>];
    };
    responses: {};
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, ResponseEnvelope<...>>
get
= 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<"/posts/:id">(path?: "/posts/:id" | undefined): Omit<ServerRouteBuilder<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithHttpMethod<RootBuilderState, "GET", TPath>>>
Defines a GET route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder}
get
("/posts/:id")
.
params<z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>(schema: z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", TSchema>>>
Defines path parameters.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
params
(import zz.
function object<{
    id: z.ZodString;
}>(shape?: {
    id: 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<{
    id: z.ZodString;
}, z.core.$strip>
object
({ id: z.ZodStringid: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string() }))
.
query<z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, z.core.$strip>>(schema: z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, "query", z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, 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<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}>(shape?: {
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, z.core.$strip>
object
({
preview: z.ZodOptional<z.ZodEnum<{
    true: "true";
    false: "false";
}>>
preview
: import zz.
enum<readonly ["true", "false"]>(values: readonly ["true", "false"], params?: string | z.core.$ZodEnumParams): z.ZodEnum<{
    true: "true";
    false: "false";
}> (+1 overload)
export enum
enum
(["true", "false"]).
ZodType<any, any, $ZodEnumInternals<{ true: "true"; false: "false"; }>>.optional(): z.ZodOptional<z.ZodEnum<{
    true: "true";
    false: "false";
}>>
optional
() }))
.
headers<z.ZodObject<{
    "x-request-id": z.ZodOptional<z.ZodString>;
}, z.core.$strip>>(schema: z.ZodObject<{
    "x-request-id": z.ZodOptional<z.ZodString>;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithRequest<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, "query", z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, z.core.$strip>>, "headers", z.ZodObject<...>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>>
Defines request headers.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
headers
(import zz.
function object<{
    "x-request-id": z.ZodOptional<z.ZodString>;
}>(shape?: {
    "x-request-id": z.ZodOptional<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<{
    "x-request-id": z.ZodOptional<z.ZodString>;
}, z.core.$strip>
object
({ "x-request-id": import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string().ZodType<any, any, $ZodStringInternals<string>>.optional(): z.ZodOptional<z.ZodString>optional() }))
.
error<"POST_NOT_FOUND", {
    readonly status: 404;
}>(code: "POST_NOT_FOUND", options?: {
    readonly status: 404;
} | undefined): Omit<ServerRouteBuilder<WithError<WithRequest<WithRequest<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, "query", z.ZodObject<{
    preview: z.ZodOptional<z.ZodEnum<{
        true: "true";
        false: "false";
    }>>;
}, z.core.$strip>>, "headers", z.ZodObject<{
    "x-request-id": z.ZodOptional<z.ZodString>;
}, z.core.$strip>>, RouteErrorClassFor<...>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>> (+1 overload)
Adds an error, the same as adding `routeError(code, options)`. The status defaults to 400.
@see{@link https://rest-rpc.vercel.app/docs/errors#define-and-throw}
error
("POST_NOT_FOUND", { status: 404status: 404 })
.
handler<ResponseEnvelope<{
    body: string;
    id: string;
    title: string;
}, NoInfer<{
    readonly headers: {
        readonly "x-powered-by": "rest-rpc";
    };
}>>>(handler: HandlerFor<{
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        query: readonly [z.ZodObject<{
            preview: z.ZodOptional<z.ZodEnum<{
                true: "true";
                false: "false";
            }>>;
        }, z.core.$strip>];
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
        headers: readonly [z.ZodObject<{
            "x-request-id": z.ZodOptional<z.ZodString>;
        }, z.core.$strip>];
    };
    responses: {};
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<...>;
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, ResponseEnvelope<...>>): HandledRoute<...>
Attaches the server handler that completes the route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
handler
(({
params: {
    id: string;
}
params
,
query: {
    preview?: "true" | "false" | undefined;
}
query
,
errors: {
    POST_NOT_FOUND: (options?: {
        message?: string | undefined;
        cookies?: readonly string[] | undefined;
        cause?: unknown;
        data?: undefined;
        headers?: undefined;
    } | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>;
}
errors
}) => {
const
const post: {
    id: string;
    title: string;
    body: string;
} | undefined
post
=
function findPost(id: string): {
    id: string;
    title: string;
    body: string;
} | undefined
findPost
(
params: {
    id: string;
}
params
.id: stringid);
if (!
const post: {
    id: string;
    title: string;
    body: string;
} | undefined
post
) throw
errors: {
    POST_NOT_FOUND: (options?: {
        message?: string | undefined;
        cookies?: readonly string[] | undefined;
        cause?: unknown;
        data?: undefined;
        headers?: undefined;
    } | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>;
}
errors
.
type POST_NOT_FOUND: (options?: {
    message?: string | undefined;
    cookies?: readonly string[] | undefined;
    cause?: unknown;
    data?: undefined;
    headers?: undefined;
} | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>
POST_NOT_FOUND
();
return
respond<{
    body: string;
    id: string;
    title: string;
}, {
    readonly headers: {
        readonly "x-powered-by": "rest-rpc";
    };
}>(body: {
    body: string;
    id: string;
    title: string;
}, options?: ({
    readonly headers: {
        readonly "x-powered-by": "rest-rpc";
    };
} & {
    headers: unknown;
}) | undefined): ResponseEnvelope<{
    body: string;
    id: string;
    title: string;
}, NoInfer<{
    readonly headers: {
        readonly "x-powered-by": "rest-rpc";
    };
}>>
Returns a response with a status or headers, such as a `content-type`, other than the defaults of a plain return value.
@remarksAny other value a handler returns is the response body, so only `respond()` results are read as responses. An `undefined` body sends no body.@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
respond
(
{ ...
const post: {
    id: string;
    title: string;
    body: string;
}
post
,
body: stringbody:
query: {
    preview?: "true" | "false" | undefined;
}
query
.preview?: "true" | "false" | undefinedpreview === "true" ?
const post: {
    id: string;
    title: string;
    body: string;
}
post
.body: stringbody.String.slice(start?: number, end?: number): string
Returns a section of a string.
@paramstart The index to the beginning of the specified portion of stringObj.@paramend The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj.
slice
(0, 40) :
const post: {
    id: string;
    title: string;
    body: string;
}
post
.body: stringbody,
}, {
headers: {
    readonly "x-powered-by": "rest-rpc";
}
headers
: { "x-powered-by": "rest-rpc" } },
); }); export const
const router: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [z.ZodObject<{
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [z.ZodObject<{
                    preview: z.ZodOptional<z.ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, z.core.$strip>];
                params: readonly [z.ZodObject<{
                    id: z.ZodString;
                }, z.core.$strip>];
                headers: readonly [z.ZodObject<{
                    "x-request-id": z.ZodOptional<z.ZodString>;
                }, z.core.$strip>];
            };
            responses: {};
            errors: {
                POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
                    readonly status: 404;
                }>;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}
router
= {
posts: {
    create: HandledRoute<{
        readonly method: "POST";
        readonly path: undefined;
        request: {
            body: readonly [z.ZodObject<{
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>];
        };
        responses: {};
        readonly metaShape?: DefaultMeta | undefined;
    }, DefaultContext, DefaultContext, {
        id: string;
        title: string;
        body: string;
    }>;
    get: HandledRoute<{
        readonly method: "GET";
        readonly path: "/posts/:id";
        request: {
            query: readonly [z.ZodObject<{
                preview: z.ZodOptional<z.ZodEnum<{
                    true: "true";
                    false: "false";
                }>>;
            }, z.core.$strip>];
            params: readonly [z.ZodObject<{
                id: z.ZodString;
            }, z.core.$strip>];
            headers: readonly [z.ZodObject<{
                "x-request-id": z.ZodOptional<z.ZodString>;
            }, z.core.$strip>];
        };
        responses: {};
        errors: {
            POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
                readonly status: 404;
            }>;
        };
        readonly metaShape?: DefaultMeta | undefined;
    }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
}
posts
: {
create: HandledRoute<{
    readonly method: "POST";
    readonly path: undefined;
    request: {
        body: readonly [z.ZodObject<{
            title: z.ZodString;
            body: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {};
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, {
    id: string;
    title: string;
    body: string;
}>
create
,
get: HandledRoute<{
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        query: readonly [z.ZodObject<{
            preview: z.ZodOptional<z.ZodEnum<{
                true: "true";
                false: "false";
            }>>;
        }, z.core.$strip>];
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
        headers: readonly [z.ZodObject<{
            "x-request-id": z.ZodOptional<z.ZodString>;
        }, z.core.$strip>];
    };
    responses: {};
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, ResponseEnvelope<...>>
get
} };
import { function createClient<TContract extends Contract, const TGlobalHeaders extends ClientHeaders = Record<never, string>>(contract: TContract, options?: CreateClientOptions<TGlobalHeaders>): ClientFor<TContract, TGlobalHeaders>
Creates a typed fetch client whose shape mirrors a contract.
@see{@link https://rest-rpc.vercel.app/docs/client/fetch-client}
createClient
} from "@rest-rpc/core";
// getContract() runs extractContract(router) at build time. import { function getContract(): typeof routergetContract } from "./contract.ts" with { type: "macro" }; const
const client: {
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}
client
=
createClient<{
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [ZodObject<{
                    title: ZodString;
                    body: ZodString;
                }, $strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [ZodObject<{
                    preview: ZodOptional<ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, $strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}, Record<...>>(contract: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [ZodObject<{
                    title: ZodString;
                    body: ZodString;
                }, $strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [ZodObject<{
                    preview: ZodOptional<ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, $strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}, options?: CreateClientOptions<...>): {
    ...;
}
Creates a typed fetch client whose shape mirrors a contract.
@see{@link https://rest-rpc.vercel.app/docs/client/fetch-client}
createClient
(function getContract(): typeof routergetContract(), { origin?: string | undefined
The origin of the server, such as `https://api.example.com`, without a path. In browsers it defaults to the page's origin.
@remarksRequired outside browsers, where a URL without an origin cannot be resolved. A trailing slash is ignored, and an origin with a path throws a `TypeError` when the client is created.
origin
: "http://localhost:3000" });
const
const created: {
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}
created
= await
const client: {
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}
client
.
posts: {
    create: (request: {
        body: {
            title: string;
            body: string;
        };
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            id: string;
            title: string;
            body: string;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
    get: (request: {
        params: {
            id: string;
        };
        headers?: {
            "x-request-id"?: string | undefined;
        } | undefined;
        query?: {
            preview?: "true" | "false" | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            body: string;
            id: string;
            title: string;
        };
        headers: Record<...> & {
            ...;
        };
        cookies: readonly string[];
    }, Error | RouteError<...>>;
}
posts
.
create: (request: {
    body: {
        title: string;
        body: string;
    };
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error>
create
({
body: {
    title: string;
    body: string;
}
body
: { title: stringtitle: "Hello", body: stringbody: "First post" },
}); const
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
= await
const client: {
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}
client
.
posts: {
    create: (request: {
        body: {
            title: string;
            body: string;
        };
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            id: string;
            title: string;
            body: string;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
    get: (request: {
        params: {
            id: string;
        };
        headers?: {
            "x-request-id"?: string | undefined;
        } | undefined;
        query?: {
            preview?: "true" | "false" | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            body: string;
            id: string;
            title: string;
        };
        headers: Record<...> & {
            ...;
        };
        cookies: readonly string[];
    }, Error | RouteError<...>>;
}
posts
.
get: (request: {
    params: {
        id: string;
    };
    headers?: {
        "x-request-id"?: string | undefined;
    } | undefined;
    query?: {
        preview?: "true" | "false" | undefined;
    } | undefined;
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, string>>>
get
({
params: {
    id: string;
}
params
: { id: stringid:
const created: {
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}
created
.
body: {
    id: string;
    title: string;
    body: string;
}
body
.id: stringid },
query?: {
    preview?: "true" | "false" | undefined;
} | undefined
query
: { preview?: "true" | "false" | undefinedpreview: "true" },
headers?: {
    "x-request-id"?: string | undefined;
} | undefined
headers
: { "x-request-id": "req_1" },
}); if (
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
.status: 200status === 200) {
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
.
body: {
    body: string;
    id: string;
    title: string;
}
body
.title: stringtitle);
}
import { function createClient<TContract extends Contract, const TGlobalHeaders extends ClientHeaders = Record<never, string>>(contract: TContract, options?: CreateClientOptions<TGlobalHeaders>): ClientFor<TContract, TGlobalHeaders>
Creates a typed fetch client whose shape mirrors a contract.
@see{@link https://rest-rpc.vercel.app/docs/client/fetch-client}
createClient
} from "@rest-rpc/core";
import {
function createTanstackQueryUtils<TClient extends TanstackQueryClient>(client: TClient & ReservedKeyCheck<TClient>, options?: {
    prefix?: QueryKey;
}): TanstackQueryUtilsFor<TClient>
Creates a TanStack Query util tree that mirrors a client.
@remarksAccepts a client created with `createClient`. Generated utils call the client's routes, create options and stable query keys; they do not create a `QueryClient` or call framework-specific hooks. Every node of the tree has `key()`, the key that matches all of its queries, so `key` is reserved in the client tree.@see{@link https://rest-rpc.vercel.app/docs/client/tanstack-query}
createTanstackQueryUtils
} from "@rest-rpc/tanstack-query";
import { function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends QueryKey = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError> (+2 overloads)
This overload is selected when `initialData` is known to be defined, so the resulting `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
@paramoptions - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined.@paramqueryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.@returnsThe current query result, typed so that `status` is `success` — or `error` if a fetch attempt fails while keeping the existing data (`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.@see{@link queryOptions } to share these options between `useQuery` and imperative APIs like `queryClient.query`.@example```tsx import { useQuery } from '@tanstack/react-query' function Posts() { // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, // so the list stays visible alongside the error. const { data, isError, error } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts, initialData: [], }) return ( <div> {isError ? <span>Error: {error.message}</span> : null} <ul> {data.map((post) => <li key={post.id}>{post.title}</li>)} </ul> </div> ) } ```
useQuery
, function useMutation<TData = unknown, TError = Error, TVariables = void, TOnMutateResult = unknown>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: QueryClient): UseMutationResult<TData, TError, TVariables, TOnMutateResult>
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. `useMutation` is the hook for that.
@paramoptions - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.@paramqueryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.@returns`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks fire only for the latest call you've made, and only while the component is still mounted — unmounting before the mutation settles removes the subscription and prevents them from firing.@throws{Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is thrown to the nearest error boundary.@see{@link mutationOptions } to share these options across multiple `useMutation` call sites, or to look the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).@example```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( <button onClick={() => addMutation.mutate('Item', { onError: (error) => console.error('Failed to add item:', error), }) } > Add </button> ) } ```@exampleRendering the mutation's own state, rather than just firing it off: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( <div> {addMutation.isPending ? ( 'Adding todo...' ) : ( <> {addMutation.isError ? ( <div>An error occurred: {addMutation.error.message}</div> ) : null} <button onClick={() => addMutation.mutate('Item')}>Add</button> </> )} </div> ) } ```@exampleOptimistic update via `onMutate`, rolling back on `onError`: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onMutate: async (newTodo) => { await queryClient.cancelQueries({ queryKey: ['todos'] }) const previousTodos = queryClient.getQueryData<Array<string>>(['todos']) queryClient.setQueryData<Array<string>>(['todos'], (old) => [ ...(old ?? []), newTodo, ]) // Passed to `onError` as `onMutateResult` if the mutation fails. return { previousTodos } }, onError: (_err, _newTodo, onMutateResult) => { queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) return ( <button onClick={() => addMutation.mutate('Item')}>Add</button> ) } ```@exampleCallbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per call instead, so you can wait for all of them when they succeed: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodos() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) async function handleAddAll(todos: Array<string>) { try { await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) } catch (error) { console.error('Failed to add todos:', error) } } return ( <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}> Add all </button> ) } ```@exampleIf some of the mutations above can fail independently of the others, and you want to know which ones did — rather than losing that information the moment the first one rejects — swap `Promise.all` for `Promise.allSettled`: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodos() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) async function handleAddAll(todos: Array<string>) { const addResults = await Promise.allSettled( todos.map((todo) => addMutation.mutateAsync(todo)), ) addResults.forEach((addResult, index) => { if (addResult.status === 'rejected') { console.error(`Failed to add "${todos[index]}":`, addResult.reason) } }) } return ( <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}> Add all </button> ) } ```
useMutation
} from "@tanstack/react-query";
const
const queryUtils: TanstackQueryTreeFor<{
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}>
queryUtils
=
createTanstackQueryUtils<{
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}>(client: {
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
} & {
    ...;
}, options?: {
    prefix?: QueryKey;
}): TanstackQueryTreeFor<...>
Creates a TanStack Query util tree that mirrors a client.
@remarksAccepts a client created with `createClient`. Generated utils call the client's routes, create options and stable query keys; they do not create a `QueryClient` or call framework-specific hooks. Every node of the tree has `key()`, the key that matches all of its queries, so `key` is reserved in the client tree.@see{@link https://rest-rpc.vercel.app/docs/client/tanstack-query}
createTanstackQueryUtils
(
createClient<{
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [ZodObject<{
                    title: ZodString;
                    body: ZodString;
                }, $strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [ZodObject<{
                    preview: ZodOptional<ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, $strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}, Record<...>>(contract: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [ZodObject<{
                    title: ZodString;
                    body: ZodString;
                }, $strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [ZodObject<{
                    preview: ZodOptional<ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, $strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}, options?: CreateClientOptions<...>): {
    ...;
}
Creates a typed fetch client whose shape mirrors a contract.
@see{@link https://rest-rpc.vercel.app/docs/client/fetch-client}
createClient
(function getContract(): typeof routergetContract(), { origin?: string | undefined
The origin of the server, such as `https://api.example.com`, without a path. In browsers it defaults to the page's origin.
@remarksRequired outside browsers, where a URL without an origin cannot be resolved. A trailing slash is ignored, and an origin with a path throws a `TypeError` when the client is created.
origin
: "http://localhost:3000" }),
); const
const post: UseQueryResult<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, string>>>
post
=
useQuery<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, string>>, {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, readonly unknown[]>(options: UndefinedInitialDataOptions<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<...>, {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, readonly unknown[]>, queryClient?: QueryClient): UseQueryResult<...> (+2 overloads)
This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may return `undefined`, so the resulting `data` can be `undefined`.
@paramoptions - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.@paramqueryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.@returnsThe current query result. `status` is `pending` if there is no cached data to display, `error` if the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience.@see{@link queryOptions } to share these options between `useQuery` and imperative APIs like `queryClient.query`.@example```tsx import { useQuery } from '@tanstack/react-query' function Posts() { const { status, data, error, isFetching } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts, }) if (status === 'pending') return 'Loading...' if (status === 'error') return <span>Error: {error.message}</span> return ( <div> <ul> {data.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> <div>{isFetching ? 'Background Updating...' : ' '}</div> </div> ) } ```@exampleThe same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: ```tsx import { useQuery } from '@tanstack/react-query' function Posts() { const { isPending, isError, data, error } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts, }) if (isPending) return 'Loading...' if (isError) return <span>Error: {error.message}</span> return ( <ul> {data.map((post) => <li key={post.id}>{post.title}</li>)} </ul> ) } ```
useQuery
(
const queryUtils: TanstackQueryTreeFor<{
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}>
queryUtils
.
posts: TanstackQueryTreeFor<{
    create: (request: {
        body: {
            title: string;
            body: string;
        };
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            id: string;
            title: string;
            body: string;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
    get: (request: {
        params: {
            id: string;
        };
        headers?: {
            "x-request-id"?: string | undefined;
        } | undefined;
        query?: {
            preview?: "true" | "false" | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            body: string;
            id: string;
            title: string;
        };
        headers: Record<...> & {
            ...;
        };
        cookies: readonly string[];
    }, Error | RouteError<...>>;
}>
posts
.
get: TanstackQueryRouteValue<(request: {
    params: {
        id: string;
    };
    headers?: {
        "x-request-id"?: string | undefined;
    } | undefined;
    query?: {
        preview?: "true" | "false" | undefined;
    } | undefined;
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, string>>>>
get
.
queryOptions: <{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}>(options: QueryOptionsFor<(request: {
    params: {
        id: string;
    };
    headers?: {
        "x-request-id"?: string | undefined;
    } | undefined;
    query?: {
        preview?: "true" | "false" | undefined;
    } | undefined;
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<...>>, {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, never>) => QueryObserverOptions<...> & {
    ...;
} (+1 overload)
queryOptions
({
request: {
    params: {
        id: string;
    };
    headers?: {
        "x-request-id"?: string | undefined;
    } | undefined;
    query?: {
        preview?: "true" | "false" | undefined;
    } | undefined;
}
request
: {
params: {
    id: string;
}
params
: { id: stringid: "post_1" },
query?: {
    preview?: "true" | "false" | undefined;
} | undefined
query
: { preview?: "true" | "false" | undefinedpreview: "true" },
}, }), ); const
const create: UseMutationResult<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown>
create
=
useMutation<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown>(options: UseMutationOptions<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown>, queryClient?: QueryClient): UseMutationResult<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown>
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. `useMutation` is the hook for that.
@paramoptions - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.@paramqueryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.@returns`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks fire only for the latest call you've made, and only while the component is still mounted — unmounting before the mutation settles removes the subscription and prevents them from firing.@throws{Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is thrown to the nearest error boundary.@see{@link mutationOptions } to share these options across multiple `useMutation` call sites, or to look the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).@example```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( <button onClick={() => addMutation.mutate('Item', { onError: (error) => console.error('Failed to add item:', error), }) } > Add </button> ) } ```@exampleRendering the mutation's own state, rather than just firing it off: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( <div> {addMutation.isPending ? ( 'Adding todo...' ) : ( <> {addMutation.isError ? ( <div>An error occurred: {addMutation.error.message}</div> ) : null} <button onClick={() => addMutation.mutate('Item')}>Add</button> </> )} </div> ) } ```@exampleOptimistic update via `onMutate`, rolling back on `onError`: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodo() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onMutate: async (newTodo) => { await queryClient.cancelQueries({ queryKey: ['todos'] }) const previousTodos = queryClient.getQueryData<Array<string>>(['todos']) queryClient.setQueryData<Array<string>>(['todos'], (old) => [ ...(old ?? []), newTodo, ]) // Passed to `onError` as `onMutateResult` if the mutation fails. return { previousTodos } }, onError: (_err, _newTodo, onMutateResult) => { queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) return ( <button onClick={() => addMutation.mutate('Item')}>Add</button> ) } ```@exampleCallbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per call instead, so you can wait for all of them when they succeed: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodos() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) async function handleAddAll(todos: Array<string>) { try { await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) } catch (error) { console.error('Failed to add todos:', error) } } return ( <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}> Add all </button> ) } ```@exampleIf some of the mutations above can fail independently of the others, and you want to know which ones did — rather than losing that information the moment the first one rejects — swap `Promise.all` for `Promise.allSettled`: ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodos() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) async function handleAddAll(todos: Array<string>) { const addResults = await Promise.allSettled( todos.map((todo) => addMutation.mutateAsync(todo)), ) addResults.forEach((addResult, index) => { if (addResult.status === 'rejected') { console.error(`Failed to add "${todos[index]}":`, addResult.reason) } }) } return ( <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}> Add all </button> ) } ```
useMutation
(
const queryUtils: TanstackQueryTreeFor<{
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}>
queryUtils
.
posts: TanstackQueryTreeFor<{
    create: (request: {
        body: {
            title: string;
            body: string;
        };
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            id: string;
            title: string;
            body: string;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
    get: (request: {
        params: {
            id: string;
        };
        headers?: {
            "x-request-id"?: string | undefined;
        } | undefined;
        query?: {
            preview?: "true" | "false" | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            body: string;
            id: string;
            title: string;
        };
        headers: Record<...> & {
            ...;
        };
        cookies: readonly string[];
    }, Error | RouteError<...>>;
}>
posts
.
create: TanstackQueryRouteValue<(request: {
    body: {
        title: string;
        body: string;
    };
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error>>
create
.
mutationOptions: (options?: MutationOptionsFor<(request: {
    body: {
        title: string;
        body: string;
    };
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error>> | undefined) => MutationOptions<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown> & {
    ...;
}
mutationOptions
());
const create: UseMutationResult<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown>
create
.
mutate: (variables: {
    body: {
        title: string;
        body: string;
    };
}, options?: MutateOptions<{
    status: 200;
    body: {
        id: string;
        title: string;
        body: string;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error, {
    body: {
        title: string;
        body: string;
    };
}, unknown> | undefined) => void
The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.
@paramvariables - The variables object to pass to the `mutationFn`.@paramoptions.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result.@paramoptions.onError - This function will fire if the mutation encounters an error and will be passed the error.@paramoptions.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error.@remarks- If you make multiple requests, `onSuccess` will fire only after the latest call you've made. - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored.
mutate
({
body: {
    title: string;
    body: string;
}
body
: { title: stringtitle: "Hello", body: stringbody: "First post" } });
import { 
function createToolsFromRoutes<TRouter extends RuntimeImplementationTree>(router: TRouter, options?: CreateToolsFromRoutesOptions): Array<AgentTool<TreeInitialContext<TRouter>> & {
    route: Omit<RouteDefinition, "meta"> & {
        path: string;
        meta?: Partial<DefaultMeta>;
    };
    routePath: readonly string[];
}>
Creates a tool for each route in a route tree, to register with an MCP server or an agent SDK. Calls run through the route's validation and middleware without HTTP.
@remarksTool arguments and results are JSON, so routes with streamed or raw responses, or a body that isn't JSON, are left out. A result is the response body, without its status, headers and cookies. A tool is named by its key path joined with `_`, and two routes whose names are the same throw when the tools are created.@see{@link https://rest-rpc.vercel.app/docs/tooling/mcp-tools}
createToolsFromRoutes
} from "@rest-rpc/server";
import * as import zz from "zod"; import {
const router: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [z.ZodObject<{
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [z.ZodObject<{
                    preview: z.ZodOptional<z.ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, z.core.$strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}
router
} from "./router.ts";
// posts_create and posts_get, to register on an MCP server or an agent SDK. export const
const tools: (AgentTool<{}> & {
    route: Omit<RouteDefinition, "meta"> & {
        path: string;
        meta?: Partial<DefaultMeta>;
    };
    routePath: readonly string[];
})[]
tools
=
createToolsFromRoutes<{
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [z.ZodObject<{
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [z.ZodObject<{
                    preview: z.ZodOptional<z.ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, z.core.$strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}>(router: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [z.ZodObject<{
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [z.ZodObject<{
                    preview: z.ZodOptional<z.ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, z.core.$strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}, options?: CreateToolsFromRoutesOptions): (AgentTool<...> & {
    ...;
})[]
Creates a tool for each route in a route tree, to register with an MCP server or an agent SDK. Calls run through the route's validation and middleware without HTTP.
@remarksTool arguments and results are JSON, so routes with streamed or raw responses, or a body that isn't JSON, are left out. A result is the response body, without its status, headers and cookies. A tool is named by its key path joined with `_`, and two routes whose names are the same throw when the tools are created.@see{@link https://rest-rpc.vercel.app/docs/tooling/mcp-tools}
createToolsFromRoutes
(
const router: {
    posts: {
        create: HandledRoute<{
            readonly method: "POST";
            readonly path: undefined;
            request: {
                body: readonly [z.ZodObject<{
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>];
            };
            responses: {};
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, {
            id: string;
            title: string;
            body: string;
        }>;
        get: HandledRoute<{
            readonly method: "GET";
            readonly path: "/posts/:id";
            request: {
                query: readonly [z.ZodObject<{
                    preview: z.ZodOptional<z.ZodEnum<{
                        true: "true";
                        false: "false";
                    }>>;
                }, z.core.$strip>];
                params: readonly [...];
                headers: readonly [...];
            };
            responses: {};
            errors: {
                ...;
            };
            readonly metaShape?: DefaultMeta | undefined;
        }, DefaultContext, DefaultContext, ResponseEnvelope<...>>;
    };
}
router
, {
schemaConverter?: SchemaConverter | undefined
Converts Standard Schema definitions into JSON Schema. Without it, or when it returns `undefined`, a segment accepts any value.
schemaConverter
: (schema: StandardSchemaV1<unknown, unknown>schema, io: "input" | "output"io) => import zz.
toJSONSchema<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>(schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, params?: z.core.ToJSONSchemaParams): z.core.ZodStandardJSONSchemaPayload<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> (+1 overload)
export toJSONSchema
toJSONSchema
(schema: StandardSchemaV1<unknown, unknown>schema as import zz.interface ZodType<out Output = unknown, out Input = unknown, out Internals extends z.core.$ZodTypeInternals<Output, Input> = z.core.$ZodTypeInternals<Output, Input>>ZodType, { io?: "input" | "output" | undefined
Whether to extract the `"input"` or `"output"` type. Relevant to transforms, defaults, coerced primitives, etc. - `"output"` — Default. Convert the output schema. - `"input"` — Convert the input schema.
io
}),
});
# No method or path defined: POST, at the path of the route's keys.
POST /posts/create HTTP/1.1
Content-Type: application/json

{ "title": "Hello", "body": "Routes return data and clients call them like functions." }
HTTP/1.1 200 OK
Content-Type: application/json

{ "id": "post_1", "title": "Hello", "body": "Routes return data and clients call them like functions." }
GET /posts/post_1?preview=true HTTP/1.1
X-Request-Id: req_1
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: rest-rpc

{ "id": "post_1", "title": "Hello", "body": "Routes return data and clients call them" }
# A defined error is sent as JSON with its status.
GET /posts/missing HTTP/1.1
HTTP/1.1 404 Not Found
Content-Type: application/json

{ "code": "POST_NOT_FOUND", "message": "POST_NOT_FOUND" }

Mistakes Fail to Compile

A request that doesn’t match the route or a read of a field it doesn’t return is a type error, in every client of the route:

const 
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
= await
const client: {
    posts: {
        create: (request: {
            body: {
                title: string;
                body: string;
            };
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                id: string;
                title: string;
                body: string;
            };
            headers: Record<string, string>;
            cookies: readonly string[];
        }, Error>;
        get: (request: {
            params: {
                id: string;
            };
            headers?: {
                "x-request-id"?: string | undefined;
            } | undefined;
            query?: {
                preview?: "true" | "false" | undefined;
            } | undefined;
        }, options?: FetchOptions | undefined) => ClientPromise<{
            status: 200;
            body: {
                body: string;
                id: string;
                title: string;
            };
            headers: Record<...> & {
                ...;
            };
            cookies: readonly string[];
        }, Error | RouteError<...>>;
    };
}
client
.
posts: {
    create: (request: {
        body: {
            title: string;
            body: string;
        };
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            id: string;
            title: string;
            body: string;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
    get: (request: {
        params: {
            id: string;
        };
        headers?: {
            "x-request-id"?: string | undefined;
        } | undefined;
        query?: {
            preview?: "true" | "false" | undefined;
        } | undefined;
    }, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            body: string;
            id: string;
            title: string;
        };
        headers: Record<...> & {
            ...;
        };
        cookies: readonly string[];
    }, Error | RouteError<...>>;
}
posts
.
get: (request: {
    params: {
        id: string;
    };
    headers?: {
        "x-request-id"?: string | undefined;
    } | undefined;
    query?: {
        preview?: "true" | "false" | undefined;
    } | undefined;
}, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}, Error | RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, string>>>
get
({
params: {
    id: string;
}
params
: { postId: "post_1" } });
Object literal may only specify known properties, and 'postId' does not exist in type '{ id: string; }'.
if (
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
.status: 200status === 200) {
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(
const response: {
    status: 200;
    body: {
        body: string;
        id: string;
        title: string;
    };
    headers: Record<string, string> & {
        readonly "x-powered-by": "rest-rpc";
    };
    cookies: readonly string[];
}
response
.
body: {
    body: string;
    id: string;
    title: string;
}
body
.titel);
Property 'titel' does not exist on type '{ body: string; id: string; title: string; }'. Did you mean 'title'?
}

Rename a field the handler returns, and every client and query that reads it stops compiling until it’s updated. For a coding agent, tsc is the check that its change is complete.

Write Shared Logic Once

A builder holds what a group of routes shares, such as context, errors and middleware. Every route built from it inherits them, typed:

const authenticated = route
	.$context<{ headers: Headers }>()
	.error("UNAUTHORIZED", { status: 401 })
	.use(({ context, errors, next }) => {
		const user = context.headers.get("authorization");
		if (!user) throw errors.UNAUTHORIZED();
		return next({ context: { user } });
	});

const router = {
	me: authenticated.get("/me").handler(({ context }) => context.user),
	posts: {
		create: authenticated
			.body(z.object({ title: z.string(), body: z.string() }))
			.handler(({ body, context }) => createPost(context.user, body)),
	},
};

Fits What You Have

  • Just HTTP: methods, paths, query, headers, statuses and content types are what they look like. Any HTTP client can call the routes.
  • Any runtime: Bun, Deno, Cloudflare Workers and Node.
  • Any framework or none: serve routes with createApp, or from Hono, Express, Fastify and others. Routes are the same either way.
  • Any schema library: Zod, Valibot, ArkType or any Standard Schema.
  • Primitives over features: authentication, caching and dependency injection are a few lines of middleware and context, written your way, instead of built-in features to configure.

Get Started

For coding agents, install the rest-rpc skill. It points them to the cheatsheet that ships with each package:

npx skills add simoalanne/rest-rpc
pnpm dlx skills add simoalanne/rest-rpc
yarn dlx skills add simoalanne/rest-rpc
bunx skills add simoalanne/rest-rpc
nubx skills add simoalanne/rest-rpc
aube dlx skills add simoalanne/rest-rpc

Common Questions

Do I have to restructure my app?

No. Keep your authentication, database access and deployment, and your framework if you have one. Add typed routes at the API boundary, and adopt the client, TanStack Query, OpenAPI, or MCP server and agent SDK tools when they’re useful.

Do I need a server framework?

No, any framework or none works. createApp serves routes without one, and any framework can serve them instead. Routes don’t change, so you can switch later.

Can I have a separate contract?

Yes. Define the interface on its own, implement it on the server, and share it with clients. See Contract-first.

What makes it good for coding agents?

A type check shows whether a change is complete, and the API has one obvious way to do each thing, so generated code looks like the docs. The skill, the cheatsheet and llms.txt give agents the docs of the installed version.

Was this page helpful?