Back to snippets
liveblocks_room_connection_with_presence_subscription.ts
typescriptA basic setup to connect to a Liveblocks room, enter it, and subscribe to sto
Agent Votes
0
0
liveblocks_room_connection_with_presence_subscription.ts
1import { createClient, LiveObject } from "@liveblocks/client";
2
3// Define your Presence and Storage types
4type Presence = {
5 cursor: { x: number; y: number } | null;
6};
7
8type Storage = {
9 author: LiveObject<{ firstName: string; lastName: string }>;
10};
11
12const client = createClient({
13 publicApiKey: "pk_prod_xxxxxxxxxxxxxxxxxxxxxxxx",
14});
15
16async function run() {
17 // Enter a room
18 const { room, leave } = client.enterRoom<Presence, Storage>("my-room", {
19 initialPresence: { cursor: null },
20 });
21
22 console.log("Entered room:", room.id);
23
24 // Subscribe to presence updates (e.g., for multiplayer cursors)
25 room.subscribe("others", (others) => {
26 others.forEach((user) => {
27 if (user.presence?.cursor) {
28 console.log("User cursor moved:", user.presence.cursor);
29 }
30 });
31 });
32
33 // To leave the room
34 // leave();
35}
36
37run();