Skip to content

Utility Process API

import { createParentPortHandler } from 'electron-messageport-trpc/utility';

Attaches a tRPC request handler to the utility process’s parentPort. This allows the main process (or, via brokering, a renderer) to call tRPC procedures running in a utility process.

interface CreateParentPortHandlerOptions<TRouter extends AnyRouter> {
router: TRouter;
parentPort: ParentPort;
createContext?: () => Promise<unknown>;
}
ParameterTypeRequiredDescription
routerAnyRouterYesYour tRPC router instance
parentPortParentPortYesThe utility process parent port from electron
createContext() => Promise<unknown>NoFactory function called for every request

A { handlers: PortHandler[] } object. Each transferred port creates one handler.

utility-worker.ts
import { createParentPortHandler } from 'electron-messageport-trpc/utility';
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
const router = t.router({
heavyComputation: t.procedure.query(async () => {
// Runs in a separate thread, not blocking the main process
return performExpensiveWork();
}),
});
createParentPortHandler({
router,
parentPort: process.parentPort,
});
// main process
import { MessageChannelMain, utilityProcess } from 'electron';
import { createTRPCClient } from '@trpc/client';
import { mainPortLink } from 'electron-messageport-trpc/main';
const child = utilityProcess.fork('utility-worker.js');
const { port1, port2 } = new MessageChannelMain();
child.postMessage({ type: 'connect' }, [port1]);
const client = createTRPCClient({
links: [mainPortLink({ port: port2 })],
});
  • CPU-intensive computation without blocking the main process
  • File processing in a background thread
  • Database operations isolated from the main process
  • Renderer-to-utility brokering when the main process should only hand off a port