🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@carverjs/multiplayer

Package Overview
Dependencies
Maintainers
2
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@carverjs/multiplayer

Serverless P2P multiplayer for CarverJS games — WebRTC mesh, lobbies, host authority, and state sync over MQTT or Firebase signaling.

latest
Source
npmnpm
Version
0.0.4
Version published
Maintainers
2
Created
Source

@carverjs/multiplayer

npm license Discord

Serverless peer-to-peer multiplayer for CarverJS games. A WebRTC data-channel mesh with pluggable signaling (MQTT or Firebase), lobbies, host authority, and three sync engines — no game server required.

Beta: CarverJS is under active development. APIs may change between minor versions until 1.0.

Install

npm install @carverjs/multiplayer
# optional — Firebase RTDB signaling (MQTT is the zero-config default)
npm install firebase

Peer dependencies: @carverjs/core, @react-three/fiber, react, react-dom. firebase is an optional peer, needed only when you choose the Firebase strategy.

How it works

Signaling (MQTT or Firebase) is used only to introduce peers and relay SDP/ICE. Once the WebRTC connection is established, all game data flows directly peer-to-peer over data channels — the signaling backend never sees gameplay traffic. One peer acts as the authoritative host; host migrates automatically if it leaves.

Quick start

Wrap your game in a provider, join a room, and exchange typed events:

import {
  MultiplayerProvider, MultiplayerBridge,
  useRoom, usePlayers, useNetworkEvents,
} from "@carverjs/multiplayer";
import { Game, World } from "@carverjs/core/components";

function App() {
  return (
    // Zero-config: free public MQTT brokers handle signaling
    <MultiplayerProvider appId="my-game">
      <Game mode="2d">
        <MultiplayerBridge>
          <World>
            <Lobby />
          </World>
        </MultiplayerBridge>
      </Game>
    </MultiplayerProvider>
  );
}

function Lobby() {
  const room = useRoom("room-code-1234", { displayName: "Ada" });
  const { players, self } = usePlayers();
  const { broadcast, onEvent } = useNetworkEvents();

  // room.connectionState, room.isHost, room.selfId, room.leave(), ...
  return <span>{players.length} players · {room.isHost ? "host" : "client"}</span>;
}

MultiplayerBridge connects the engine's render loop to the network layer; place it inside <Game> and around the scene that uses sync hooks.

Signaling strategies

// Free, zero-config (default): public MQTT brokers
<MultiplayerProvider appId="my-game">

// Firebase Realtime Database (bring your own project)
<MultiplayerProvider
  appId="my-game"
  strategy={{ type: "firebase", databaseURL: "https://your-project.firebaseio.com" }}
>

STUN / TURN

Defaults to public STUN. Add a TURN relay so peers behind restrictive NATs or firewalls can still connect:

<MultiplayerProvider
  appId="my-game"
  iceServers={[
    { urls: "stun:stun.cloudflare.com:3478" },
    { urls: "turn:turn.cloudflare.com:3478", username: "...", credential: "..." },
  ]}
>

TURN is only used when a direct connection fails. For same-network testing, STUN alone is enough.

Connection reliability

The WebRTC mesh self-heals while peers are connecting — no configuration required. Each link has a single deterministic initiator (the peer with the lower id); if a pair hasn't reached connected shortly after the first offer, the initiator automatically re-sends it with an ICE restart, a few times over roughly 20 seconds, until the link comes up. This transparently recovers the transient failures of serverless signaling:

  • an offer, answer, or ICE candidate dropped in transit;
  • ICE candidates that arrive before the peer is ready (buffered, not discarded);
  • slow STUN candidate gathering on a cold network.

Every pair in the mesh establishes independently and recovers on its own, so a hiccup on one link no longer leaves two players unable to see each other — the rest of the room is unaffected and the stalled pair re-handshakes itself. This makes STUN-only deployments reliable in practice. A TURN relay is still required only for pairs that genuinely can't traverse each other's NAT (e.g. two symmetric/CGNAT endpoints) — STUN cannot relay those no matter how many times the handshake retries.

Sync modes

useMultiplayer({ mode }) selects how world state is replicated:

ModeUse it forHow
eventsturn-based, sandbox, chat, infrequent state changestyped messages over a reliable, ordered channel
snapshotreal-time movementhost broadcasts delta-compressed snapshots; clients interpolate
predictionfast-paced actionclient-side prediction with server reconciliation and rollback
import { useMultiplayer } from "@carverjs/multiplayer";

function Scene() {
  useMultiplayer({ mode: "snapshot", tickRate: 60 });
  // ... actors marked networked are replicated automatically
}

Hooks

HookPurpose
useRoom(roomId, opts)Join / leave a room; exposes connection state, host, and self id.
useLobby()Browse advertised rooms.
usePlayers()Live player list plus self.
useHost()Host-only room controls — room state, lock, kick, host transfer.
useMultiplayer({ mode })Drive the sync engine for a scene.
useNetworkEvents()Typed broadcast / sendEvent / onEvent messaging.
useNetworkState()Networked spawn / despawn helpers.

Host authority & migration

Exactly one peer is the authoritative host. If it disconnects, the engine migrates host to another peer automatically, and host election is deterministic and consistent across all peers.

To pin a specific peer as host — for example the room creator that owns the world — advertise a host priority in player metadata. The lowest priority wins; peers that advertise none rank last (preserving the default lowest-peer-id election among them):

useRoom(roomId, {
  displayName: name,
  playerMetadata: { hostPriority: isCreator ? 0 : 1 },
});

Advanced exports

For lower-level control, the package also exports:

  • MqttStrategy, FirebaseStrategy — construct or inject a signaling strategy directly.
  • NetworkSimulator — inject artificial latency and packet loss during development.
  • InterestManager — area-of-interest filtering for large worlds.
  • InputBuffer, computeJustPressed — input history and edge detection for prediction.
  • DebugOverlay — on-screen network stats.

License

MIT — MoneyTales EduTech Private Limited

FAQs

Package last updated on 18 Jun 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts