Quickstart
Learn how to quickly setup and get started with @pluv/io.
Installation
pluv.io is broken up into multiple packages, so that you can install only what you need, particular to your codebase and framework selections.
Purpose | Location | Install command |
---|---|---|
Register websockets and custom events | Server | npm install @pluv/io |
Call and listen to events. Interact with shared storage | Client | npm install @pluv/client |
React-bindings for @pluv/client | Client | npm install @pluv/react |
Adapter for Node.js runtime | Server | npm install @pluv/platform-node ws |
Adapter for Cloudflare Workers runtime | Server | npm install @pluv/platform-cloudflare |
yjs CRDT | Both | npm install @pluv/crdt-yjs yjs |
loro CRDT | Both | npm install @pluv/crdt-loro loro-crdt |
Installation Example
Here is an example installation for npm, assuming you are building for Node.js, React and TypeScript.
1# For the server2npm install @pluv/io @pluv/platform-node3# Server peer-dependencies4npm install ws zod56# For the client7npm install @pluv/react8# Client peer-dependencies9npm install react react-dom zod1011# If you want to use storage features, install your preferred CRDT12npm install @pluv/crdt-yjs yjs
Defining a backend PluvIO instance
Let's step through how we'd put together a real-time API for Node.js. In this example, this API will define 2 type-safe events.
Create PluvIO instance
Define an io (websocket client) instance on the server codebase:
1// backend/io.ts23import { yjs } from "@pluv/crdt-yjs";4import { createIO } from "@pluv/io";5import { platformNode } from "@pluv/platform-node";67export const io = createIO({8 // Optional: Only if you require CRDT features9 crdt: yjs,10 platform: platformNode(),11});1213// Export the websocket client io type, instead of the client itself14export type AppPluvIO = typeof io;
Create type-safe server events
Use io.event
to define type-safe websocket events on the io instance. The two properties on the event function are:
input
: zod validation schema that validates and casts the input for the event.resolver
: This is the implementation of the event. It accepts an input of the validated input of the incoming event, and returns an event record to emit back to the frontend client.
1// backend/io.ts23import { yjs } from "@pluv/crdt-yjs";4import { createIO } from "@pluv/io";5import { platformNode } from "@pluv/platform-node";6import { z } from "zod";78export const io = createIO({9 // Optional: Only if you require CRDT features10 crdt: yjs,11 platform: platformNode(),12})13 // When event "SEND_MESSAGE" is sent by the frontend and received14 // on the server15 .event("SEND_MESSAGE", {16 // Define a zod validation schema for the input17 input: z.object({18 message: z.string(),19 }),20 // Emit a "MESSAGE_RECEIVED" from the server to the client21 resolver: ({ message }) => ({ MESSAGE_RECEIVED: { message } }),22 })23 .event("EMIT_EMOJI", {24 input: z.object({25 emojiCode: z.number(),26 }),27 resolver: ({ emojiCode }) => ({ EMOJI_RECEIVED: { emojiCode } }),28 });2930// Export the io type instance of the io itself31export type AppPluvIO = typeof io;
Integrate PluvIO with ws
Important: Demonstration is for Node.js only.
Create a WS.Server
instance from ws on Node.js. For more information, read about createPluvHandler.
1// backend/server.ts23import { createPluvHandler } from "@pluv/platform-node";4import express from "express";5import Http from "http";6import { io } from "./io";78const PORT = 3000;910const app = express();11const server = Http.createServer();1213const Pluv = createPluvHandler({ io, server });1415// WS.Server instance from the ws module16const wsServer = Pluv.createWsServer();1718app.use(Pluv.handler);1920server.listen(PORT);
Connecting the frontend to PluvIO
Now that the io instance is setup on the backend, we can setup the frontend client and connect the exported io type from the server.
Create the React bundle
1// frontend/io.ts23import { yjs } from "@pluv/crdt-yjs";4import { createBundle, createClient, y } from "@pluv/react";5import type { AppPluvIO } from "server/io";67const client = createClient<AppPluvIO>();89export const {10 // factories11 createRoomBundle,1213 // components14 PluvProvider,1516 // hooks17 useClient,18} = createBundle(client);1920export const {21 // components22 MockedRoomProvider,23 PluvRoomProvider,2425 // hooks26 useBroadcast,27 useConnection,28 useEvent,29 useMyPresence,30 useMyself,31 useOther,32 useOthers,33 useRoom,34 useStorage,35} = createRoomBundle({36 initialStorage: yjs.doc(() => ({37 messages: yjs.array(["hello world!"]),38 })),39});
Wrap with your pluv.io providers
Wrap your component with PluvRoomProvider
to connect to a realtime room and enable the rest of your room react hooks.
1// frontend/Room.tsx23import { FC } from "react";4import { PluvRoomProvider } from "./io";5import { ChatRoom } from "./ChatRoom";67export const Room: FC = () => {8 return (9 <PluvRoomProvider room="my-example-room">10 <ChatRoom />11 </PluvRoomProvider>12 );13};
Send and receive events
Use useBroadcast
and useEvent
to send and receive type-safe events in your React component.
1// frontend/ChatRoom.tsx23import { FC, useCallback, useState } from "react";4import { emojiMap } from "./emojiMap";5import { useBroadcast, useEvent } from "./io";67export const ChatRoom: FC = () => {8 const broadcast = useBroadcast();910 const [messages. setMessages] = useState<string[]>([]);1112 useEvent("MESSAGE_RECEIVED", ({ data }) => {13 // ^? (property) data: { message: string }14 setMessages((prev) => [...prev, data.message]);15 });1617 useEvent("EMOJI_RECEIVED", ({ data }) => {18 // ^? (property) data: { emojiCode: number }19 const emoji = emojiMap[data.emojiCode];2021 console.log(emoji);22 });2324 const onMessage = useCallback((message: string): void => {25 // 2nd parameter will be statically typed from server/io.ts26 broadcast("SEND_MESSAGE", { message });27 }, [broadcast]);2829 const onEmoji = useCallback((emojiCode: number): void => {30 broadcast("EMIT_EMOJI", { emojiCode });31 }, [broadcast]);3233 // ...34};
Next steps
This example only scratches the surface of the realtime capabilities offered by pluv.io.