Message Port
oRPC offers built-in support for common Message Port implementations, enabling easy internal communication between different processes.
| Environment | Documentation |
|---|---|
| Electron Message Port | Adapter Guide |
| Browser (extension background to popup/content, window to window, etc.) | Adapter Guide |
| Node.js Worker Threads Port | Adapter Guide |
Basic Usage
Message Ports work by establishing two endpoints that can communicate with each other:
const channel = new MessageChannel()
const serverPort = channel.port1
const clientPort = channel.port2import { RPCHandler } from '@orpc/server/message-port'
const handler = new RPCHandler(router)
handler.upgrade(serverPort, {
context: {}, // Provide initial context if needed
})
serverPort.start()import { RPCLink } from '@orpc/client/message-port'
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.
Transfer
By default, oRPC serializes request/response messages to string/binary data before sending over message port. If needed, you can define the transfer option to utilize full power of MessagePort: postMessage() method, such as transferring ownership of objects to the other side or support unserializable objects like OffscreenCanvas.
const handler = new RPCHandler(router, {
experimental_transfer: (message, port) => {
const transfer = deepFindTransferableObjects(message) // implement your own logic
return transfer.length ? transfer : null // only enable when needed
}
})const link = new RPCLink({
port: clientPort,
experimental_transfer: (message) => {
const transfer = deepFindTransferableObjects(message) // implement your own logic
return transfer.length ? transfer : null // only enable when needed
}
})WARNING
When transfer returns an array, messages using the structured clone algorithm for sending, which doesn't support all data types such as Event Iterator's Metadata. So I recommend you only enable this when needed.
TIP
The transfer option run after RPC JSON Serializer so you can combine them together to support more data types.
