Next.js Example

Build live multiplayer cursors in a Next.js app, end to end.

This walks through a complete live-cursors stage in a Next.js App Router project: one shared socket, a hook over the built-in cursor events, and a component that renders everyone's pointer. It's the same approach as the Live Cursors demo, split into the files a real app would have.

npm install socket.io-client

Point the app at your server. Use the address from the Overview tab in Slash Socket — localhost while you're developing, your LAN IP or forwarded domain for other devices.

.env.local

Socket.IO only runs in the browser, so the connection lives in a client-only module. Keeping a single instance means every component shares one connection instead of opening a new one per render.

lib/socket.ts

The hook reports your pointer with cursor_move and turns cursor_update broadcasts into a list of cursors. Positions are sent in pixels together with the stage size (vw, vh), so each client can convert them to fractions and draw them in the same relative spot on a stage of any size. Sending x: -1 is the convention for "my cursor left the stage".

hooks/use-live-cursors.ts

The component is the stage: it measures pointer positions relative to itself and draws the other cursors with percentage offsets. The server never echoes your own cursor_move back to you, so only other people's pointers show up. Don't put a CSS transition on the cursor position — it only adds delay. If you have many people on one stage, write positions straight to each cursor's DOM node instead of React state, the way the Live Cursors demo does, so the page doesn't re-render on every move.

components/live-cursors.tsx
app/page.tsx
  1. Start the server in Slash Socket.
  2. Run your app with next dev and open it in two browser windows.
  3. Move the pointer in one window — it appears in the other, and both show up in the Clients tab with their live positions.

Want to see it against the slash.tools demo? Open slash.tools/socket?socket=http://localhost:3001 next to your app while the server is running, and cursors from both pages share the same stage. Browsers may ask for permission before a public page can reach localhost.

Slash Socket serves plain HTTP. A page loaded over HTTPS can reach http://localhost, but not a plain-HTTP server anywhere else, because browsers block mixed content. To use it from a deployed HTTPS site, put the server behind something that terminates TLS (a reverse proxy or a tunnel) and point NEXT_PUBLIC_SLASH_SOCKET_URL at that https:// address.