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 server
2npm install @pluv/io @pluv/platform-cloudflare
3# Server peer-dependencies
4npm install yjs zod

Create PluvIO instance

Define an io (websocket client) instance on the server codebase:

1// backend/io.ts
2
3import { yjs } from "@pluv/crdt-yjs";
4import { createIO } from "@pluv/io";
5import { platformCloudflare } from "@pluv/platform-cloudflare";
6import { eq } from "drizzle-orm";
7import { drizzle } from "drizzle-orm/d1";
8import { schema } from "./schema";
9
10type Env = {
11 DB: D1Database;
12};
13
14export const io = createIO({
15 crdt: yjs,
16 platform: platformCloudflare<Env>(),
17 // Example of using Cloudflare's D1 database with drizzle-orm
18 getInitialStorage: async ({ env, room }) => {
19 const db = drizzle(env.DB, { schema });
20
21 const existingRoom = await db
22 .select({ encodedState: schema.rooms.encodedState })
23 .from(schema.rooms)
24 .where(eq(schema.rooms.name, room))
25 .get();
26
27 return existingRoom?.encodedState ?? null;
28 },
29 onRoomDeleted: async ({ encodedState, env, room }) => {
30 const db = drizzle(env.DB, { schema });
31
32 await db
33 .insert(schema.rooms)
34 .values({
35 name: room,
36 encodedState,
37 })
38 .onConflictDoUpdate({
39 target: schema.rooms.name,
40 set: { encodedState },
41 })
42 .run();
43 },
44});
45
46// Export the websocket client io type, instead of the client itself
47export 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.ts
2
3import { type InferIORoom } from "@pluv/io";
4import { AppPluvIO, io } from "./io";
5
6export class RoomDurableObject implements DurableObject {
7 private _io: InferIORoom<AppPluvIO>;
8
9 constructor(state: DurableObjectState) {
10 this._io = io.getRoom(state.id.toString());
11 }
12
13 async fetch(request: Request) {
14 if (request.headers.get("Upgrade") !== "WebSocket") {
15 return new Response("Expected WebSocket", { status: 400 });
16 }
17
18 const { 0: client, 1: server } = new WebSocketPair();
19
20 await this._io.register(server);
21
22 return new Response(null, { status: 101, webSocket: client });
23 }
24}

Forward request to RoomDurableObject

Lastly, integrate your RoomDurableObject with your Cloudflare Worker's default handler:

1// server/index.ts
2
3const parseRoomId = (url: string): string => {
4 /* get room from req.url */
5};
6
7const handler = {
8 async fetch(req: Request, env: Env): Promise<Response> {
9 const roomId = parseRoomId(req.url);
10 // In wrangler.toml:
11 // [durable_objects]
12 // bindings = [{ name = "rooms", class_name = "RoomDurableObject" }]
13 const durableObjectId = env.rooms.idFromString(roomId);
14
15 const room = env.rooms.get(durableObjectId);
16
17 return room.fetch(request);
18 },
19};
20
21export default handler;

createPluvHandler

If you don't need to modify your DurableObject or Cloudflare Worker handler too specifically, @pluv/platform-cloudflare also provides a function createPluvHandler to create a DurableObject and handler for you automatically.

1import { yjs } from "@pluv/crdt-yjs";
2import { createIO } from "@pluv/io";
3import { createPluvHandler, platformCloudflare } from "@pluv/platform-cloudflare";
4
5const io = createIO({
6 crdt: yjs,
7 platform: platformCloudflare(),
8});
9
10const Pluv = createPluvHandler({
11 // Your PluvIO instance
12 io,
13 // Your durable object binding, defined in wrangler.toml
14 binding: "rooms",
15 // Optional: Specify the base path from which endpoints are defined
16 endpoint: "/api/pluv", // default
17 // If your PluvIO instance defines authorization, add your authorization
18 // logic here. Return a user if authorized, return null or throw an error
19 // if not authorized.
20 authorize(request: Request, roomId: string): Promise<User> {
21 return {
22 id: "abc123",
23 name: "leedavidcs"
24 };
25 },
26 // Optional: If you want to modify your response before it is returned
27 modify: (request, response) => {
28 if (request.headers.get("Upgrade") === "websocket") return response;
29
30 // Add custom headers if you want
31 response.headers.append("access-control-allow-origin", "*");
32
33 return response;
34 },
35});
36
37// Export your Cloudflare Worker DurableObject with your own custom name
38// Then in wrangler.toml:
39// [durable_objects]
40// bindings = [{ name = "rooms", class_name = "RoomDurableObject" }]
41export const RoomDurableObject = Pluv.DurableObject;
42
43// Export your Cloudflare Worker handler
44export default Pluv.handler;
45
46// Alternatively, define your own custom handler
47export default {
48 async fetch(request: Request, env: Env): Promise<Response> {
49 const response = await Pluv.fetch(request, env);
50
51 // matched with the Pluv handler, return response
52 if (response) return response;
53
54 // didn't match with Pluv handler, add your own worker logic
55 // ...
56
57 return new Response("Not found", { status: 404 });
58 }
59};