Web Workers Adapter
Use oRPC for typesafe communication with Web Workers via the Message Port Adapter.
Web Workers allow JavaScript code to run in background threads, separate from the main thread of a web page. This prevents blocking the UI while performing computationally intensive tasks. Web Workers are also supported in modern runtimes like Bun, Deno, etc.
With oRPC, you can establish typesafe communication channels between your main thread and Web Workers through the Message Port Adapter.
Web Worker
Configure your Web Worker to handle oRPC requests by upgrading it with a message port handler:
import { onError } from '@orpc/server'
import { RPCHandler } from '@orpc/server/message-port'
const handler = new RPCHandler(router, {
interceptors: [
onError((error) => {
console.error(error)
}),
],
})
handler.upgrade(self, {
context: {} // Provide initial context if needed
})
Main Thread
Create a link to communicate with your Web Worker:
import { RPCLink } from '@orpc/client/message-port'
export const link = new RPCLink({
port: new Worker('some-worker.js')
})
Using Web Workers in Vite Applications?
You can leverage the Vite Web Workers feature for streamlined development:
import { RPCLink } from '@orpc/client/message-port'
import SomeWorker from './some-worker.ts?worker'
export const link = new RPCLink({
port: new SomeWorker()
})