Multiplayer

Turn-based challenges through shared game state, and realtime rooms for live play with invites owned by the platform.

Remix has two multiplayer models. Challenges are turn-based: players take turns pushing a shared game state, and the platform notifies whoever is up. Realtime rooms seat up to 12 players for live play, and the platform handles the room, the invites and the connections. A game that needs a trusted referee, a persistent world or more players can run its rooms on a game server Remix hosts for it.

Turn-Based Challenges

Challenges run in the Remix app on iOS and Android and on remix.gg. A challenge session has several players in GameInfo and a usersTurnId naming who the platform is waiting on. Trust it over your own inference; the platform rejects state saves from anyone else.

const info = await sdk.ready()
const me = info.player.id
const myTurn = info.usersTurnId === me

Push shared state after a move. The first id in alertUserIds takes the turn, and every id must belong to a player in the challenge:

sdk.multiplayer.actions.saveGameState({
  gameState: { moves },
  alertUserIds: [nextPlayerId],
})

Receive other players' moves, validate them, and refute anything invalid:

sdk.onGameStateUpdated((update) => {
  if (!update) return resetBoard()
  try {
    applyMoves(update.gameState.moves)
  } catch {
    sdk.multiplayer.actions.refuteGameState({ gameStateId: update.id })
  }
})

End the match with every player's score:

sdk.multiplayer.actions.gameOver({
  scores: [{ playerId: a, score: 1 }, { playerId: b, score: 0 }],
})

Use the player ids from GameInfo; they are the only ids the platform accepts.

Realtime Rooms

sdk.realtime gives your game rooms, players and messages, and the platform runs everything underneath. Rooms work on Remix Desktop, remix.gg and the Remix mobile app.

const room = await sdk.realtime.createRoom()        // take the first seat
// or
const room = await sdk.realtime.joinRoom(code)      // join by invite code

sdk.realtime.room   // the live room, or null
room.selfId
room.peers          // live roster, self excluded, in seat order
room.isHost         // this player owns the room
room.isAuthority    // this player's device runs the match

room.send({ t: 'start', at })                       // to everyone, reliable and ordered
room.send(snapshot, { reliable: false })            // per-frame state, never resent
room.sendTo(userId, { t: 'ready' })                 // to one player

room.onMessage((fromUserId, data) => handle(fromUserId, data))
room.onPeerJoin((peer) => addRacer(peer))
room.onPeerLeave((peer) => removeRacer(peer))
// reason: 'left' | 'expired' | 'offline' | 'closed' | 'kicked'
room.onEnded((reason) => showLobby(reason))
// transport trouble worth telling the player; the room keeps trying
room.onError((message) => toast(message))

room.invite()       // opens the platform's invite flow
room.kick(userId)   // owner only; that player's room ends with 'kicked'
room.leave()

A message is any JSON-serializable value, or an ArrayBuffer or typed array, which arrives as an ArrayBuffer. Sends are reliable and ordered by default, for lobby state, countdowns and results; pass { reliable: false } for the frequent state stream, where a late packet is worth less than the next one. send and sendTo return false when the message was dropped for at least one player, and every room on… call returns a function that unsubscribes.

room.code is an invite credential, not something to show players. Call room.invite() from a player action and the platform shares the invite. It has no delivery result, so wait for onPeerJoin before saying a friend joined.

Mount the lobby from sdk.realtime.onRoom, not only from your own create or join call: accepting an invite boots the game already seated, and onRoom replays a room seated before you subscribed. onRoomError is where a failed platform join (full, expired, wrong game) surfaces.

createRoom and joinRoom reject with a RealtimeRoomError whose code is room_not_found, room_full, game_mismatch (an invite for another game), no_game_id (the game is not published yet) or join_failed. Rooms need a signed-in player; a guest's request fails with join_failed and the platform offers sign-in.

One live room at a time: a new create or join leaves the current room. A room seats up to 12 players, so a thirteenth join fails with room_full. Seat order (oldest first) is the deterministic tiebreak when peers disagree.

The Studio preview on remix.gg answers createRoom and joinRoom with a local room that has no other players, so you can build the lobby there; it cannot run a game server. Remix Desktop's Play view opens real rooms, on your draft's game server when the game has one (it falls back to a local room when you are signed out or the game is not saved to Remix yet).

Play With Friends Before You Publish

In Remix Desktop, start a multiplayer game in the Play view as a player would. The room is real, on your game's own server if it has one, and you invite friends to it from your game's invite or the Play view's Invite, which opens Remix's invite sheet. Everyone you invite plays the build in your workspace, in the room with you, and their game updates each time you change yours, so you never publish just to test with someone. Friends open the link in a browser or in Remix Desktop; a game made for computers needs a computer. Choose Stop Sharing to end it; the link also stops working once you close Remix. Sharing pauses while you publish, so the build being reviewed is the one that goes live; friends get that build, and Resume Sharing carries on from your workspace.

Nothing played this way counts: no scores, Bits or achievements are recorded until the game is published.

Authority

The room owner (hostUserId, isHost) runs the lobby and is the only player who can kick. When the owner leaves, the oldest seat takes over and onHostChange fires. The authority (authorityId, isAuthority) is the player whose device runs the match, usually someone else. Simulate on isAuthority, never on isHost.

Call room.electAuthority() from your lobby's Start action once everyone is seated. It resolves with the id of the best-connected player, as the SDK measures it, and every player hears onAuthorityChange; it rejects if the room ends or the vote does not settle. authorityId is null before the first election and while the SDK replaces an authority who left. Pause on null, and have the new authority resynchronize the match, because match state does not carry over. room.quality(userId) reports this device's round trip and loss to a player, for a connection indicator.

Route guest inputs to the authority with sendTo. Guests predict locally, the authority settles outcomes, snapshots flow back. Keep wall time, simulation ticks, input sequence and packet sequence separate, and never let a network stall stretch a physics step. A rules engine that runs identically on every peer is the foundation; the transport is the easy part.

Without a game server, anything that needs a trusted referee runs on the authority's device, which is still a player's device.

Game Servers

A game can ship server code that Remix runs for it. Ask Remix Desktop for game servers and it writes the server, uploads it when you save and publish, and wires the game to use it. Players join exactly as before: invites, links and joining a friend work the same, and room codes stay hidden.

Declare the server in remix.json and export it from its entry:

"server": { "entry": "server/main.ts", "kind": "session", "maxPlayers": 8, "tickRate": 20 }
import { GameServer, type Player } from 'remix:server'

export class Server extends GameServer {
  onJoin(player: Player) {
    this.send(player.id, { type: 'welcome' })
  }
  onMessage(player: Player, message: unknown) {
    // Validate the input, update the world.
  }
  onTick(dt: number) {
    this.broadcast({ type: 'state' })
  }
}
  • session servers live while a room has players and forget everything when it empties: matches, lobbies, rounds.
  • persistent servers are one shared world per game, split automatically into instances of maxPlayers. Each instance keeps its storage for ever, sleeps while nobody is there, and is told how long it slept when it wakes, so it can catch up.

A room's server can start again mid-match with no warning, when Remix restarts the room or one of your server's calls fails: its memory is empty, onStart runs with reason: 'restart', and onJoin runs again for every player still in the room. The same happens each time you change server code while friends are playing your unpublished game with you: the room restarts on the new code with reason: 'update', and everyone reconnects to it. Keep what a match cannot lose (the round, scores, teams, deadlines) in this.storage, which survives, write it when it changes, and read it back in onStart. Ask each client again for anything only it knows, and end the round rather than leave players waiting on state the server no longer has.

On the client nothing changes but who you talk to: in a server room room.server is true, room.send() goes to the server, messages arrive from 'server', and the server is the authority. A server room holds up to 256 players and runs up to 30 ticks a second. Server code may import other files of your game and nothing else: no packages, network or browser APIs. Keep each room's state on this: variables at module level are shared by every room of your game on the same machine.

For more than a few dozen players, do not broadcast the whole crowd every tick: what each tick sends grows with the square of the room. Keep a SpatialInterest index from remix:server on this, update it from your simulation, and send each player their own state plus the nearest players it returns:

import { GameServer, SpatialInterest } from 'remix:server'

export class Server extends GameServer {
  interest = new SpatialInterest({ cellSize: 16, maxEntries: 256 })
  // In onTick, after moving a body: this.interest.set(id, body, body.place), then
  // this.send(id, { self: body, nearby: this.interest.query(body, { radius: 48, limit: 32, space: body.place, exclude: id }) })
}

Remove players with interest.delete(id) when they leave, and draw the nearby set with instancing so the device's budget, not the room's size, decides how many you render.

When players move their own characters and the server only passes their states on (a hub, a town, a lobby), three helpers carry a state from one screen to the next with the time it was true:

// Client, every frame: send on an even beat, stamped with this clock.
const pacer = sdk.realtime.pacer({ rate: 15 })
const send = pacer.due(changedSinceLastSent)
if (send) room.send({ type: 'pose', ...pose, time: send.time }, { reliable: send.reliable })

// Server: pass each state on once, to whoever should see it.
import { GameServer, PresenceRelay } from 'remix:server'
export class Server extends GameServer {
  presence = new PresenceRelay()
  onMessage(player, m) { this.presence.set(player.id, { x: m.x, z: m.z, yaw: m.yaw }, m.time) }
  onLeave(player) { this.presence.delete(player.id) }
  onTick() {
    for (const viewer of this.players.keys()) {
      const updates = this.presence.updates(viewer, this.players.keys())
      if (updates.length > 0) this.send(viewer, { type: 'poses', updates })
    }
  }
}

// Client: one playback per remote player; draw it every frame.
const playback = sdk.realtime.playback({ rate: 15 })
playback.push(update.time, update.state) // on arrival
const f = playback.frame() // blend f.from toward f.to by f.alpha

A server that re-sends the latest state on its own clock makes steady movement stutter on every screen, which is what PresenceRelay avoids. Give updates whatever set a viewer should see, and add their own party after any distance query: distance should never hide the friends they came with.