Local Link
A link for direct procedure calls without HTTP overhead
On this page
localLink is a terminating link that allows you to make tRPC procedure calls directly in your application without going through HTTP.
Usage
import { createTRPCClient, localLink } from '@trpc/client';
import type { AppRouter } from './server';
import { appRouter } from './server';
const client = createTRPCClient<AppRouter>({
links: [
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);
},
}),
],
});Features
- Direct procedure calls without HTTP overhead
- Full support for queries, mutations, and subscriptions
- Automatic error handling and transformation
- Support for abort signals
- Type-safe context creation
Options
The localLink accepts the following options:
type LocalLinkOptions<TRouter extends AnyRouter> = {
router: TRouter;
createContext: (opts: {
info: { signal: AbortSignal };
}) => Promise<inferRouterContext<TRouter>>;
onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;
} & TransformerOptions<inferClientTypes<TRouter>>;router
The tRPC router instance to use for procedure calls.
createContext
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.
It receives info.signal, which aborts when the call is cancelled, for example when you pass signal to .query() or unsubscribe. Pass it on to slow work like database or fetch() calls. The same signal reaches your procedures as opts.signal. If the call is cancelled before or while the context is created, the procedure doesn't run.
import { localLink } from '@trpc/client';
localLink({
router: appRouter,
createContext: async (opts) => {
const session = await getSession({ signal: opts.info.signal });
return { session };
},
});onError
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.
transformer
Optional input/output transformers for serialization/deserialization of data.
Notes
- It's recommended to use this link in scenarios where you need direct procedure calls without HTTP
- For most client-side applications, you should use the
httpLinkor other HTTP-based links instead - The link supports all tRPC features including queries, mutations, and subscriptions
- Error handling and transformation are handled automatically, just like with HTTP-based links