Worker Threads Integration
Use Node.js Worker Threads with oRPC for type-safe inter-thread communication via the Message Port Adapter. Before proceeding, we recommend reviewing the Node.js Worker Thread API.
Worker Thread
Listen for a MessagePort
sent from the main thread and upgrade it:
ts
import { parentPort } from 'node:worker_threads'
import { experimental_RPCHandler as RPCHandler } from '@orpc/server/message-port'
const handler = new RPCHandler(router)
parentPort.on('message', (message) => {
if (message instanceof MessagePort) {
handler.upgrade(message)
message.start()
}
})
Main Thread
Create a MessageChannel
, send one port to the thread worker, and use the other to initialize the client link:
ts
import { MessageChannel, Worker } from 'node:worker_threads'
import { experimental_RPCLink as RPCLink } from '@orpc/client/message-port'
const { port1: clientPort, port2: serverPort } = new MessageChannel()
const worker = new Worker('some-worker.js')
worker.postMessage(serverPort, [serverPort])
const link = new RPCLink({
port: clientPort
})
clientPort.start()
INFO
This only shows how to configure the link. For full client examples, see Client-Side Clients.