www/docs/client/links/localLink.mdx
localLink is a terminating link that allows you to make tRPC procedure calls directly in your application without going through HTTP.
:::info
We have prefixed this as unstable_ as it's a new API, but you're safe to use it! Read more.
:::
// @filename: server.ts
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const appRouter = t.router({});
export type AppRouter = typeof appRouter;
// @filename: client.ts
// ---cut---
import { createTRPCClient, unstable_localLink } from '@trpc/client';
import type { AppRouter } from './server';
import { appRouter } from './server';
const client = createTRPCClient<AppRouter>({
links: [
unstable_localLink({
router: appRouter,
createContext: async () => {
// Create your context here
return {};
},
onError: (opts) => {
// Log errors here, similarly to how you would in an API route
console.error('Error:', opts.error);
},
}),
],
});
The localLink accepts the following options:
type AnyRouter = any;
type inferRouterContext<T> = any;
type inferClientTypes<T> = any;
type ErrorHandlerOptions<T> = any;
type TransformerOptions<T> = {};
// ---cut---
type LocalLinkOptions<TRouter extends AnyRouter> = {
router: TRouter;
createContext: () => Promise<inferRouterContext<TRouter>>;
onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;
} & TransformerOptions<inferClientTypes<TRouter>>;
The tRPC router instance to use for procedure calls.
A function that creates the context for each procedure call. This is called for each request and should return a promise that resolves to the context object.
An optional error handler that is called when an error occurs during a procedure call. It receives the error, operation type, path, input, and context.
Optional input/output transformers for serialization/deserialization of data.
httpLink or other HTTP-based links instead