Cloudflare Workers
pluv.io supports building real-time APIs with Cloudflare Workers through their Durable Objects API. You can define your handler and your DurableObject manually if you need more control, but if you'd like to get started quickly, check out createPluvHandler.
Using with Cloudflare Workers (manual)
Let's step through how we'd put together a real-time API for Cloudflare Workers. The examples below assumes a basic understanding of Cloudflare Workers and Durable Objects.
Install dependencies
1# For the server2npm install @pluv/io @pluv/platform-cloudflare3# Server peer-dependencies4npm install yjs zod
Create PluvIO instance
Define an io (websocket client) instance on the server codebase:
1// backend/io.ts23import { createIO } from "@pluv/io";4import { platformCloudflare } from "@pluv/platform-cloudflare";56export const io = createIO({ platform: platformCloudflare() });78// Export the websocket client io type, instead of the client itself9export type AppPluvIO = typeof io;
Attach to a RoomDurableObject
Next, create a RoomDurableObject
and attach our new pluv.io instance to the room:
1// server/RoomDurableObject.ts23import { type InferIORoom } from "@pluv/io";4import { AppPluvIO, io } from "./io";56export class RoomDurableObject implements DurableObject {7 private _io: InferIORoom<AppPluvIO>;89 constructor(state: DurableObjectState) {10 this._io = io.getRoom(state.id.toString());11 }1213 async fetch(request: Request) {14 const isWebSocketRequest = request.headers.get("Upgrade") === "WebSocket";1516 if (!isWebSocketRequest) {17 return new Response("Expected WebSocket", { status: 400 });18 }1920 const { 0: client, 1: server } = new WebSocketPair();2122 await this._io.register(server);2324 return new Response(null, { status: 101, webSocket: client });25 }26}
Forward request to RoomDurableObject
Lastly, integrate your RoomDurableObject
with your Cloudflare Worker's default handler:
1// server/index.ts23const parseRoomId = (url: string): string => {4 /* get room from req.url */5};67const handler = {8 async fetch(req: Request, env: Env): Promise<Response> {9 const roomId = parseRoomId(req.url);10 const durableObjectId = env.rooms.idFromString(roomId);1112 const room = env.rooms.get(durableObjectId);1314 return room.fetch(request);15 },16};1718export default handler;
createPluvHandler
If you don't need to modify your DurableObject or Cloudflare Worker handler too specifically, @pluv/platform-node also provides a function createPluvHandler
to create a DurableObject and handler for you automatically.
1import { createIO } from "@pluv/io";2import { createPluvHandler, platformCloudflare } from "@pluv/platform-cloudflare";34const io = createIO({ platform: platformCloudflare() });56const Pluv = createPluvHandler({7 // Your PluvIO instance8 io,9 // Your durable object binding, defined in wrangler.toml10 binding: "rooms",11 // If your PluvIO instance defines authorization, add your authorization12 // logic here. Return a user if authorized, return null or throw an error13 // if not authorized.14 authorize(request: Request, roomId: string): Promise<User> {15 return {16 id: "abc123",17 name: "leedavidcs"18 };19 },20 // Optional: If you want to modify your response before it is returned21 modify: (request, response) => {22 if (request.headers.get("Upgrade") === "websocket") return response;2324 // Add custom headers if you want25 response.headers.append("access-control-allow-origin", "*");2627 return response;28 },29});3031// Export your Cloudflare Worker DurableObject with your own custom name32// Then in wrangler.toml:33// [durable_objects]34// bindings = [{ name = "rooms", class_name = "RoomDurableObject" }]35export const RoomDurableObject = Pluv.DurableObject;3637// Export your Cloudflare Worker handler38export default Pluv.handler;3940// Alternatively, define your own custom handler41export default {42 async fetch(request: Request, env: Env): Promise<Response> {43 const response = await Pluv.fetch(request, env);4445 // matched with the Pluv handler, return response46 if (response) return response;4748 // didn't match with Pluv handler, add your own worker logic49 // ...5051 return new Response("Not found", { status: 404 });52 }53};