Back to Blog

Multiplayer Cursors in 50 Lines of React

December 2, 2026
9 min read
Five people working on laptops around a shared wooden table.

If anyone else has this page open right now, you can see their cursor moving over it, and they can see yours. Figma made this feel normal for design files. It works just as well on a proposal, a dashboard or a blog post, and it takes much less code than you’d expect: about 25 lines on the server and 25 in React.

Live on this page

Connecting…

What you actually need

Live cursors sound like a database problem. They aren’t. Nobody needs to know where your mouse was five minutes ago, so nothing gets saved. You need three things:

  1. A way for each browser to send its pointer position a few times a second.
  2. Something in the middle that passes each position on to everyone else on the same page.
  3. Code in each browser that draws the other cursors.

The middle part is the only interesting choice. It has to hold open connections and know who else is on the same page. A plain serverless function can’t do that, because each request might land on a different machine.

Why a Durable Object

A Cloudflare Durable Object is a small server object that Cloudflare runs in exactly one place at a time. Ask for the object called multiplayer-cursors-in-react from anywhere in the world and you reach the same one. That makes one object per page a natural fit: it holds that page’s WebSockets and nothing else.

The other reason is hibernation. With the hibernation API, Cloudflare keeps the WebSocket connections open but lets the object itself sleep between messages. You pay while it’s handling messages, not while twenty readers sit on a paragraph without moving. For a blog that’s the difference between free and a monthly bill.

The server: about 25 lines

index.js (Cloudflare Worker)
import { DurableObject } from 'cloudflare:workers';

export class Room extends DurableObject {
  fetch() {
    const [client, server] = Object.values(new WebSocketPair());
    this.ctx.acceptWebSocket(server);
    server.serializeAttachment({ id: crypto.randomUUID().slice(0, 8) });
    return new Response(null, { status: 101, webSocket: client });
  }

  webSocketMessage(ws, raw) {
    const { x, y } = JSON.parse(raw);
    this.broadcast(ws, { type: 'move', id: ws.deserializeAttachment().id, x, y });
  }

  webSocketClose(ws) {
    this.broadcast(ws, { type: 'leave', id: ws.deserializeAttachment().id });
  }

  broadcast(from, msg) {
    for (const peer of this.ctx.getWebSockets())
      if (peer !== from) peer.send(JSON.stringify(msg));
  }
}

export default {
  fetch(req, env) {
    const room = new URL(req.url).pathname.split('/').pop();
    return env.ROOM.get(env.ROOM.idFromName(room)).fetch(req);
  },
};

Reading it from the bottom up: the Worker takes the page name from the URL and forwards the request to the Durable Object with that name. The object accepts the WebSocket with acceptWebSocket, which is what turns hibernation on, and attaches a short random id to the connection. When a message arrives it tags the position with the sender’s id and sends it to everyone else. When someone leaves, it tells the others to remove that cursor.

The config tells Cloudflare which class is the Durable Object:

wrangler.jsonc
{
  "name": "blog-cursors",
  "main": "index.js",
  "compatibility_date": "2026-04-15",
  "durable_objects": { "bindings": [{ "name": "ROOM", "class_name": "Room" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }]
}

The React side: about 25 lines

useCursors.ts
function useCursors(room: string, area: RefObject<HTMLElement | null>) {
  const [peers, setPeers] = useState<Record<string, { x: number; y: number }>>({});

  useEffect(() => {
    const ws = new WebSocket(`wss://cursors.example.com/room/${room}`);
    ws.onmessage = (e) => {
      const m = JSON.parse(e.data);
      setPeers((all) => {
        const next = { ...all };
        if (m.type === 'move') next[m.id] = { x: m.x, y: m.y };
        else delete next[m.id];
        return next;
      });
    };
    const onMove = (e: PointerEvent) => {
      const r = area.current!.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width;
      const y = (e.clientY - r.top) / r.height;
      if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ x, y }));
    };
    window.addEventListener('pointermove', onMove);
    return () => {
      window.removeEventListener('pointermove', onMove);
      ws.close();
    };
  }, [room, area]);

  return peers;
}

The hook opens a socket for the page, keeps a map of everyone else’s positions, and sends your own position on every pointer move. Rendering is a map over that object:

Article.tsx
<div ref={area} className="relative">
  <Article />
  {Object.entries(peers).map(([id, p]) => (
    <Cursor key={id} style={{ position: 'absolute', left: `${p.x * 100}%`, top: `${p.y * 100}%` }} />
  ))}
</div>

Positions are sent as fractions of the article’s width and height, not as pixels. Someone on a 1440-pixel monitor and someone on a laptop see different layouts, so a raw pixel position would put a cursor next to a different paragraph on each screen. A fraction lands on roughly the same spot in the text. It isn’t exact when the text reflows to a different number of lines, but it’s close enough to show what someone is reading.

What the version on this page adds

The 50-line version works, and I’d happily demo it. The one running here has some extra code, mostly to keep it cheap and hard to abuse:

  • Throttling. The browser sends at most one position every 50 milliseconds, and always the latest one. Raw pointermove can fire well over 100 times a second on a fast mouse.
  • Server-side limits. The Worker only accepts connections from this site, ignores messages over 200 characters, drops anything past 40 messages a second from one reader, clamps positions to 0–1 and caps a page at 50 readers.
  • Leaving properly. When you switch tabs or move the mouse out of the window, your cursor disappears for everyone else instead of freezing in place. Cursors that haven’t moved for a minute are cleared too.
  • Reconnecting. If the connection drops, the hook retries after 2, 4, 8 seconds and so on, up to about a minute, so a server hiccup doesn’t become a flood of reconnects.
  • Presence count. The server sends the number of open connections whenever someone joins or leaves, which drives the “reading now” label in the corner.
  • Mouse only. Phones and tablets don’t have a hovering pointer, so touch readers see everyone else’s cursors but don’t send their own.
  • Smooth movement. Each cursor eases between positions over 100 milliseconds, so 20 updates a second looks like continuous motion. That’s turned off for anyone who has reduced motion switched on.

Privacy

Nothing here identifies you. The server sees a position and a random id, and your name is made up from that id, which is why you might be a Patient Heron today. Nothing is written to storage, and when everyone has left the page, the object has nothing to remember.

Other ways to build it

If you’d rather not run any server code, hosted services do this for you. Liveblocks has presence and cursors as ready-made React hooks, Supabase Realtime has presence and broadcast channels, and PartyKit (now part of Cloudflare) wraps Durable Objects in a friendlier API. They’re worth it when cursors are the start of something bigger, like shared editing or comments.

For a single feature like this one, I prefer the 50 lines. There’s no extra account or extra bill, and nothing in it I can’t read in one sitting.

Where it’s worth adding

  • Proposals and pitch decks you walk a client through on a call. Both of you see what the other is pointing at.
  • Dashboards a team looks at together, so “this number here” means the same number for everyone.
  • Launch pages and live events, where seeing other people arrive is half the fun.
  • Docs and internal tools, as a light way of showing who else is looking at the same thing before two people edit it at once.

And if you’re reading this with nobody else around, open it in a second window and wave at yourself.

Frequently Asked Questions

How do multiplayer cursors work on a website?
Each visitor’s browser sends its pointer position to a small server over a WebSocket several times a second. The server passes each position on to everyone else viewing the same page, and each browser draws the other people’s cursors on top of the content.

What is a Cloudflare Durable Object?
A Durable Object is a small piece of server code with its own state that Cloudflare runs in one place at a time. Every request for the same name reaches the same object, which makes it a natural home for a chat room, a shared document or the list of people on one page.

How much does it cost to run live cursors?
Very little at blog scale. With WebSocket hibernation, a Durable Object is only billed while it is handling messages, not while connections sit idle, and Cloudflare’s free plan includes a daily allowance of requests. Throttling each browser to around 20 updates a second keeps message counts low.

Do live cursors collect personal data?
They do not have to. The version on this page sends only a position, gives each reader a random name like Swift Otter, and stores nothing. The server forgets everything when the last person leaves.

Want your product to feel shared?

Presence, live cursors and real-time updates make dashboards, proposals and design tools feel alive. I can add them to a Next.js app without a big new service to maintain.

Connecting to live cursors…