Build IPC for Electron with tRPC
- Expose APIs from Electron's main process to one or more render processes.
- Build fully type-safe IPC.
- Secure alternative to opening servers on localhost.
- Subscription support coming soon.
# Using pnpm
pnpm add electron-trpc
# Using yarn
yarn add electron-trpc
# Using npm
npm install --save electron-trpc
-
Add your tRPC router to the Electron main process using
createIPCHandler
:import { app, ipcMain } from 'electron'; import { createIPCHandler } from 'electron-trpc'; import { router, createContext } from './api'; app.on('ready', () => { createIPCHandler({ ipcMain, router, createContext })); // ... });
-
Expose the IPC to the render process from the preload file:
import { contextBridge, ipcRenderer } from 'electron'; import { exposeElectronTRPC } from 'electron-trpc'; process.once('loaded', async () => { exposeElectronTRPC({ contextBridge, ipcRenderer }); });
Note:
electron-trpc
depends oncontextIsolation
being enabled, which is the default. -
When creating the client in the render process, use the
ipcLink
(instead of the HTTP or batch HTTP links):import * as trpc from '@trpc/client'; import { ipcLink } from 'electron-trpc'; export const trpcClient = trpc.createTRPCClient({ links: [ipcLink()], });
-
Now you can use the client in your render process as you normally would (e.g. using
@trpc/react
).