Free Three.js Article

Three.js Multiplayer Game:
Authoritative Server with WebSockets

By Shane Brumback ·

How I build a three js multiplayer game: a server that owns the rules, WebSockets, snapshot buffering and interpolation so other players move smoothly.

Three.js Multiplayer WebSockets Networking
Read the Tutorial → Play the Game

The Short Answer

A three js multiplayer game keeps every player in one shared world by sending small messages over a WebSocket. An authoritative server owns the rules: it decides what is allowed, who hears each message and what the official game state is. Each browser moves its own player right away (client-side prediction) and draws everyone else a little in the past, sliding smoothly between buffered snapshots (interpolation).

Facts

  • The scene behind this article is the arena from the matching tutorial: players are capsules on a round neon floor, and the three you see are simulated bots.
  • My shared multiplayer relay answers at wss://relay.indieforgestudio.com. It checks the page Origin at the handshake, rate-limits each socket, whitelists every field per game and only routes a message to the same game mode and room.
  • The tutorial demo sends 10 position messages per second and draws other players 200 ms in the past, with at most 200 ms of extrapolation when a packet is late.
  • Arena Blasters sends its online matches through the same relay with its own message schema.

Introduction

When I build a multiplayer game, from AI Tic-Tac-Toe to Arena Blasters, the first prototype usually looks the same: two browser tabs, one WebSocket, and a player that jitters across the screen. Getting the messages from one browser to another is the easy part. The hard part is deciding who to trust and making other players look smooth when their updates arrive late, early or not at all.

This article is the why. I explain the three ideas that turn a jittery prototype into a three js multiplayer game that feels good: an authoritative server, client-side prediction and snapshot interpolation. The matching premium tutorial, Three.js Multiplayer Game Tutorial: Smooth Players with Interpolation, is the how: a small shared arena that joins a room on my live relay, with a toggle that turns interpolation off so you can see the difference for yourself.

What Is an Authoritative Server in a Three.js Multiplayer Game?

In a "trust the client" setup, each browser announces where its player is and everyone believes it. That falls apart the moment someone opens the developer tools and sends a position on the other side of the map.

An authoritative server flips that around. The server holds the official copy of the game. Browsers send what they want to do, the server checks it against the rules (speed, walls, fire rate, health) and only the result goes out to everyone else.

There is a sliding scale here, and I want to be honest about where my own setup sits. My shared relay at wss://relay.indieforgestudio.com is a validating relay. It rejects pages from origins it does not know, rate-limits every socket, rebuilds each message from a per-game whitelist of fields with clamped numbers, caps how fast a player can fire, and only routes a message to sockets in the same game mode and room. It does not run the movement simulation itself. A fully authoritative server goes one step further and moves every player itself, like the sketch further down.

How Do WebSockets Work in a Three JS Multiplayer Game?

A WebSocket starts as a normal HTTP request and then upgrades into a long-lived, two-way connection. In the browser you need new WebSocket(url), onmessage and send(); three.js just draws whatever positions your code ends up with.

What matters is the shape of the messages. On my relay every room game tags each message with a mode (which game), a room (which match) and a player_id with a game prefix. The tutorial demo uses a schema the relay already allows for shanebrumback.com and its own room, so it never mixes with real matches of other games. Keep messages small and send them at a steady rate: the demo sends 10 position updates a second, which is plenty for walking players.

Snapshot Interpolation: Why Other Players Look Smooth

Your screen draws 60 or more frames a second, but another player's position might arrive 10 times a second, and never on a perfect beat. If you snap each remote player to the newest message, they move in little hops. If you ease them toward the newest message, they drift and cut corners.

Snapshot interpolation is the fix most real-time games use. Keep the last few snapshots for each remote player on an evenly spaced timeline: packets are sent on a steady beat but arrive unevenly, so stamp them with the time they should have arrived, not the raw arrival time. When you draw a frame, pick a moment slightly in the past, for example 200 ms ago, find the two snapshots on either side of it and blend between them. You always have real data on both sides, so the motion is smooth and accurate. The cost is a small, fixed delay on other players, which nobody notices when it is around 100 to 150 ms.

When a packet is late, guess ahead from the last two snapshots for a short time (extrapolation), then hold still. In the tutorial demo a yellow ring marks the newest packet, so you can watch the smoothed avatar trail it.

Client-Side Prediction Basics

Your own player is different. Waiting for a server round trip before you move feels terrible, so the browser moves your player the instant you press a key. That is client-side prediction. It works because the browser runs the same movement rules the server does: the same speed, the same arena edge, the same pillars. If the rules match, the server agrees with the prediction almost every time.

When it does not agree, a fully authoritative game sends a correction and the client replays its unconfirmed inputs on top (reconciliation). The tutorial keeps to the basics: instant local movement, shared rules and interpolated remote players.

A Minimal Authoritative Server in Node.js

Here is the authoritative pattern in its smallest form. Browsers send only their input (which way they want to walk), clamped to -1..1. The server moves every player itself ten times a second, keeps them inside the arena and broadcasts one snapshot with everyone's position. Change ALLOWED_ORIGIN to your own site. This is a teaching sketch, not the code running on my relay.

// server.js: a minimal authoritative arena server (Node 18+, npm install ws)
import { WebSocketServer } from 'ws';

const ALLOWED_ORIGIN = 'https://your-site.example';
const ARENA_RADIUS = 17, MAX_SPEED = 6, TICK_HZ = 10;
const wss = new WebSocketServer({ port: 8080 });
const players = new Map();   // socket -> { id, x, z, yaw, ix, iz }
let nextId = 1;

wss.on('connection', (ws, req) => {
  if (req.headers.origin !== ALLOWED_ORIGIN) return ws.close(1008, 'origin');
  const p = { id: 'p' + nextId++, x: 0, z: 0, yaw: 0, ix: 0, iz: 0 };
  players.set(ws, p);
  ws.send(JSON.stringify({ type: 'welcome', id: p.id }));
  ws.on('message', (raw) => {
    let m;
    try { m = JSON.parse(raw); } catch { return; }
    if (m.type !== 'input') return;                         // whitelist message types
    p.ix = Math.max(-1, Math.min(1, Number(m.ix) || 0));    // the client sends intent only
    p.iz = Math.max(-1, Math.min(1, Number(m.iz) || 0));
  });
  ws.on('close', () => players.delete(ws));
});

setInterval(() => {                                         // the server owns the simulation
  const dt = 1 / TICK_HZ;
  for (const p of players.values()) {
    const len = Math.hypot(p.ix, p.iz);
    if (len > 0) {
      p.x += (p.ix / len) * MAX_SPEED * dt;
      p.z += (p.iz / len) * MAX_SPEED * dt;
      p.yaw = Math.atan2(p.ix, p.iz);
    }
    const r = Math.hypot(p.x, p.z);
    if (r > ARENA_RADIUS) { p.x *= ARENA_RADIUS / r; p.z *= ARENA_RADIUS / r; }
  }
  const snapshot = JSON.stringify({ type: 'snapshot', t: Date.now(),
    players: [...players.values()].map(({ id, x, z, yaw }) => ({ id, x: +x.toFixed(2), z: +z.toFixed(2), yaw: +yaw.toFixed(3) })) });
  for (const ws of players.keys()) if (ws.readyState === 1) ws.send(snapshot);
}, 1000 / TICK_HZ);

The browser sends { type: 'input', ix, iz } when its keys change and feeds each snapshot into the same interpolation buffer the tutorial builds.

How To Build a Three.js Multiplayer Game, Step by Step

  1. Decide who is in charge. Let the server own the rules and the official state; browsers send what the player wants to do.
  2. Open one WebSocket per player. Tag every message with a game mode, a room and a player id so the server can validate and route it.
  3. Predict your own player. Move the local player the instant a key is pressed, using the same movement rules the server uses, so the guess is almost always right.
  4. Buffer and interpolate everyone else. Stamp each remote snapshot on an evenly spaced timeline (not its jittery arrival time), draw remote players about 150 to 200 ms in the past and slide between the two snapshots around that moment.
  5. Plan for bad networks. Extrapolate briefly when a packet is late and drop players who leave or go silent.

In a Real Game: Arena Blasters

Arena Blasters is my free 3D arena shooter, and its online matches run through the same shared relay as the tutorial demo, with their own message schema and public map rooms. You can read more about the game in Arena Blasters: Free 3D Arena Shooter in Your Browser.

If you want a full shooter to learn from, the Three.js Multiplayer FPS Game Starter tutorial covers rooms, hits and AI soldiers. It smooths remote players by easing them toward their newest position. This new tutorial focuses on the snapshot buffer instead, so the two make a good pair.

Frequently Asked Questions

What is an authoritative server in a three js multiplayer game?

It is the one place that decides what really happened. Browsers send inputs, the server checks them against the rules, and everyone only sees what the server accepted, so a modified browser cannot teleport.

Do I need WebSockets for a Three.js multiplayer game?

For real-time movement, a WebSocket is the simplest choice that works in every modern browser: one connection open in both directions.

Why do other players stutter even when my frame rate is high?

Updates arrive maybe 10 times a second, never evenly spaced. Jumping to the newest one makes players hop; interpolation draws them slightly in the past between two known positions.

Is the live demo free?

Yes. The live demo in the tutorial is free: sign in free with Google to launch it. The step-by-step code and the full source file are for members.

Can I use your relay for my own game?

No. My relay only accepts my own sites and approved message schemas, so a copy elsewhere falls back to the offline demo. Use the Node.js sketch above as a start for your own server.

Build It Yourself

The premium tutorial has the live demo (sign in free with Google), the step-by-step code and the one-click Launch. Or jump into a real match in Arena Blasters.