Renderer API
import { portLink, getPort,} from 'electron-messageport-trpc/renderer';portLink(opts)
Section titled “portLink(opts)”Creates a tRPC link that communicates over a MessagePort. Use this as a link in your createTRPCClient configuration.
Parameters
Section titled “Parameters”interface PortLinkOptions { port: MessagePort | Promise<MessagePort>;}| Parameter | Type | Required | Description |
|---|---|---|---|
port | MessagePort | Promise<MessagePort> | Yes | The renderer-side MessagePort, or a promise that resolves to one |
Returns
Section titled “Returns”TRPCLink<TRouter> — a tRPC link function compatible with createTRPCClient.
Example
Section titled “Example”import { createTRPCClient } from '@trpc/client';import { portLink, getPort } from 'electron-messageport-trpc/renderer';import type { AppRouter } from '../main/router';
const trpc = createTRPCClient<AppRouter>({ links: [ portLink({ port: getPort() }), ],});How It Works
Section titled “How It Works”- On first use, the link resolves the port promise and sets up a
messageevent listener. - Each request is assigned a unique numeric ID.
- Requests are sent as
ClientMessageobjects viaport.postMessage(). - Responses are matched by ID and dispatched to the appropriate observer.
- For subscriptions, the observer receives
onStarted, multipleonDatacallbacks,onStoppedwhen the server-side iterable completes, and finallyonComplete. - When a subscription is unsubscribed, a
subscription.stopmessage is sent.
getPort()
Section titled “getPort()”Returns a Promise<MessagePort> that resolves to the port exposed by the preload script.
Parameters
Section titled “Parameters”None.
Returns
Section titled “Returns”Promise<MessagePort>
Throws
Section titled “Throws”Throws an Error if exposePortReceiver() was not called in the preload script (i.e., window.electronTRPCPort is undefined).
Error: electronTRPCPort not found. Did you call exposePortReceiver() in your preload script?Example
Section titled “Example”import { getPort } from 'electron-messageport-trpc/renderer';
const port = await getPort();// Use the port directly, or pass it to portLink