Web Workers 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 type-safe communication channels between your main thread and Web Workers. For additional context, see the Message Port Adapter guide.
Web Worker
Configure your Web Worker to handle oRPC requests by upgrading it with a message port handler:
ts
import { RPCHandler } from '@orpc/server/message-port'
const handler = new RPCHandler(router)
handler.upgrade(self, {
context: {}, // Provide initial context if needed
})
Main Thread
Create a link to communicate with your Web Worker:
ts
import { RPCLink } from '@orpc/client/message-port'
export const link = new RPCLink({
port: new Worker('some-worker.ts')
})
Using Web Workers in Vite Applications?
You can leverage Vite Web Workers feature for streamlined development:
ts
import SomeWorker from './some-worker.ts?worker'
import { RPCLink } from '@orpc/client/message-port'
export const link = new RPCLink({
port: new SomeWorker()
})
INFO
This only shows how to configure the link. For full client examples, see Client-Side Clients.