pluv.io is in preview! Please wait for a v1.0.0 stable release before using this in production.

API Reference

createIO

Returns a PluvIO instance.

Creates a server-side PluvIO client that will create rooms to register your websockets to. Below will show a available configurations for createIO. To learn more about createIO, read Authorization, Cloudflare Workers, Node.js and PubSub.

1import { yjs } from "@pluv/crdt-yjs";
2import { createIO } from "@pluv/io";
3import { platformNode } from "@pluv/platform-node";
4import { z } from "zod";
5import { db } from "./db";
6
7const io = createIO({
8 // Optional: if provided, defines authorization for rooms created by io
9 authorize: {
10 // If required is false, users can authenticate for a room to
11 // attach an identity to their presence. Otherwise they will be
12 // anonymous.
13 required: true,
14 // The secret for generating your JWT
15 secret: process.env.PLUV_AUTH_SECRET!,
16 // The shape of your user object. `id` must always be required.
17 user: z.object({
18 id: z.string(),
19 // Here is an additional field we wish to add.
20 name: z.string(),
21 }),
22 },
23 // Optional. Specify to use Yjs CRDT for storage.
24 // This is required only if/when you wish to use storage features.
25 crdt: yjs,
26 // Optional. Only needed to load persisted storage for rooms.
27 // Load storage for a newly created room.
28 getInitialStorage: async ({ room }) => {
29 const existingRoom = await db.room.findUnique({ where: { room } });
30
31 return existingRoom?.encodedState ?? null;
32 },
33 // Enable @pluv/io for Node.js
34 platform: platformNode(),
35 // Optional. Only needed for persisting storage for rooms.
36 // Before the room is destroyed, persist the state to a database to load
37 // when the room is re-created.
38 onRoomDeleted: async ({ encodedState, room }) => {
39 await db.room.upsert({
40 where: { room },
41 create: { encodedState, room },
42 update: { encodedState },
43 });
44 },
45 // Optional. It is unnecessary to save the storage state in this listener.
46 // If a room already exists, users will load the currently active storage
47 // before the storage from initialStorage.
48 onStorageUpdated: ({ encodedState, room }) => {
49 console.log(room, encodedState);
50 },
51});

PluvIO

This is the client returned by createIO.

createToken

Returns Promise<string>.

Creates a JWT for a user trying to connect to a room. This should be called within a custom authentication endpoint you define. See Authorization for more information.

1const token = await io.createToken({
2 // If using @platform/node
3 req: req as IncomingMessage,
4 // If using @platform/cloudflare
5 // This is the env from the Cloudflare worker handler's fetch function
6 env: env as Env,
7 // ...
8 room: "my-example-room",
9 user: {
10 id: "abc123",
11 name: "leedavidcs",
12 },
13});

event

Returns PluvIO.

Adds a new type-safe event to be broadcasted from PluvClient. See Define Events for more information.

1import { createIO } from "@pluv/io";
2import { platformNode } from "@pluv/platform-node";
3import { z } from "zod";
4
5const io = createIO({
6 platform: platformNode(),
7})
8 // When event "SEND_MESSAGE" is sent by the frontend and received
9 // on the server
10 .event("SEND_MESSAGE", {
11 // Define a zod validation schema for the input
12 input: z.object({
13 message: z.string(),
14 }),
15 // Emit a "MESSAGE_RECEIVED" from the server to the client
16 resolver: ({ message }) => ({ MESSAGE_RECEIVED: { message } }),
17 })
18 .event("EMIT_EMOJI", {
19 input: z.object({
20 emojiCode: z.number(),
21 }),
22 resolver: ({ emojiCode }) => ({ EMOJI_RECEIVED: { emojiCode } }),
23 });

getRoom

Returns IORoom.

Retrieves a room by room name if it already exists. If the room doesn't already exist, the room is created and returned.

1const room = io.getRoom("my-example-room");

IORoom

This is the room returned by PluvIO.getRoom. This is what websockets are registered to.

broadcast

Returns void.

Broadcasts an event to all connected websockets to the room.

1room.broadcast("EMIT_EMOJI", {
2 emojiCode: 123,
3});

id

Type of string.

This is the id of the room, when the room was created.

1const roomId = room.id;

register

Returns Promise<void>.

Registers a websocket to the room. Accepts a secondary options parameter to pass-in a token for authorizing the room. Read Cloudflare Workers, Node.js and Authorization to learn more.

1// const token: string = ...
2
3room.register(webSocket, { token })