Skip to content

Message Port

oRPC offers built-in support for common Message Port implementations, enabling easy internal communication between different processes.

EnvironmentDocumentation
Electron Message PortAdapter Guide
Browser (extension background to popup/content, window to window, etc.)Adapter Guide
Node.js Worker Threads PortAdapter Guide

Basic Usage

Message Ports work by establishing two endpoints that can communicate with each other:

bridge
ts
const channel = new MessageChannel()
const serverPort = channel.port1
const clientPort = channel.port2
server
ts
import { RPCHandler } from '@orpc/server/message-port'

const handler = new RPCHandler(router)

handler.upgrade(serverPort, {
  context: {}, // Provide initial context if needed
})

serverPort.start()
client
ts
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.

ts
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
  }
})
ts
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.

Released under the MIT License.