Electron Adapter
Use oRPC for typesafe communication between Electron processes via the Message Port Adapter.
Establish typesafe communication between processes in Electron using the Message Port Adapter. Before you start, we recommend reading the MessagePorts in Electron guide.
Main Process
Listen for a port sent from the renderer, then upgrade it:
import { onError } from '@orpc/server'
import { RPCHandler } from '@orpc/server/message-port'
import { app, ipcMain } from 'electron'
const handler = new RPCHandler(router, {
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
app.whenReady().then(() => {
ipcMain.on('start-orpc-server', async (event) => {
const [serverPort] = event.ports
handler.upgrade(serverPort, {
context: {} // Provide initial context if needed
})
serverPort.start()
})
})
Preload Process
Receive the port from the renderer and forward it to the main process:
import { ipcRenderer } from 'electron'
window.addEventListener('message', (event) => {
if (event.data === 'start-orpc-client') {
const [serverPort] = event.ports
ipcRenderer.postMessage('start-orpc-server', null, [serverPort])
}
})
Renderer Process
Create a MessageChannel, send one port to the preload script, and use the other to initialize the client link:
import { RPCLink } from '@orpc/client/message-port'
const { port1: clientPort, port2: serverPort } = new MessageChannel()
window.postMessage('start-orpc-client', '*', [serverPort])
const link = new RPCLink({
port: clientPort,
})
clientPort.start()