Skip to content

Renderer API

import {
portLink,
getPort,
} from 'electron-messageport-trpc/renderer';

Creates a tRPC link that communicates over a MessagePort. Use this as a link in your createTRPCClient configuration.

interface PortLinkOptions {
port: MessagePort | Promise<MessagePort>;
}
ParameterTypeRequiredDescription
portMessagePort | Promise<MessagePort>YesThe renderer-side MessagePort, or a promise that resolves to one

TRPCLink<TRouter> — a tRPC link function compatible with createTRPCClient.

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() }),
],
});
  1. On first use, the link resolves the port promise and sets up a message event listener.
  2. Each request is assigned a unique numeric ID.
  3. Requests are sent as ClientMessage objects via port.postMessage().
  4. Responses are matched by ID and dispatched to the appropriate observer.
  5. For subscriptions, the observer receives onStarted, multiple onData callbacks, onStopped when the server-side iterable completes, and finally onComplete.
  6. When a subscription is unsubscribed, a subscription.stop message is sent.

Returns a Promise<MessagePort> that resolves to the port exposed by the preload script.

None.

Promise<MessagePort>

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?
import { getPort } from 'electron-messageport-trpc/renderer';
const port = await getPort();
// Use the port directly, or pass it to portLink