← Headless Host

HBInit and BOLTInit reference

Both initializers support the normal HaxBall configuration and room API, and both return a room with the room.bolt API. HBInit enables match statistics and vote-kick. Use BOLTInit when you want to configure the BOLT features yourself.

const room = HBInit({
  roomName: "My room",
  maxPlayers: 12,
  public: true,
  noPlayer: true
});

Quick example

const room = BOLTInit({
  roomName: "My room",
  maxPlayers: 12,
  public: true,
  noPlayer: true,

  // Optional. Add a fresh HaxBall headless token to publish there too.
  token: "YOUR_HAXBALL_TOKEN",

  bolt: {
    afk: true,
    bots: true,
    voteKick: true,
    statistics: 'builtin', // or 'off', or { read } to run your own (see below)
    eloLabel: "My ELO"
  }
});

room.onPlayerJoin = async (player) => {
  const elo = await loadMyElo(player.auth);
  room.bolt.setElo(player.id, elo);
};

BOLTInit configuration

Put these fields inside bolt. Every boolean feature is enabled by default. Set it to false when your script provides that feature itself.

FieldTypeWhat it enables
afkbooleanAFK controls and AFK state in the BOLT room menu.
botsbooleanBOLT bot controls. Up to 16 bots when captain picking is disabled.
captainbooleanCaptain picking and its balancing bot. This also requires the bot runtime.
voteKickbooleanVote creation, voting, results, and automatic kicks.
statistics'builtin' | 'custom' | 'off'Who produces the live possession, goals, assists, saves, passing, and performance statistics. 'builtin' (default): BOLT tracks them. 'custom': your room publishes its own with setMatchStatistics. 'off': none. A room has exactly one source; mixing them would make the BOLT UI flicker between the two.
eloLabelstringLabel shown beside room-owned ELO values. It is trimmed to 30 characters and defaults to ROOM ELO.

The normal token field is optional. Without it, the room is published only on BOLT. With a fresh HaxBall headless token, the same room is also published on HaxBall. Share the BOLT room link in both cases.

If registration fails, the headless page shows the reason and closes the incomplete room. Invalid or expired HaxBall tokens are called out directly. Fix the problem and call HBInit or BOLTInit again; refreshing the page is not required.

room.bolt methods

Lifecycle at a glance

  1. Initialization: HBInit and BOLTInit return the room with room.bolt ready. Register command listeners now.
  2. Room link: BOLT publishes the enabled feature list after the room is registered. You do not need to trigger this.
  3. Player activity: Set ELO values when players join or their ELO changes. Publish custom UI state whenever that state changes.
  4. Shutdown: In the browser runtime, keep the page open while hosting. In boltgame.js, keep the Node.js process running. Closing either host closes the room and removes its listeners and temporary state.

setElo(gameId, elo)

When: Call it after you know a player's ELO (your room's skill rating, an integer; not the per-match performance score from the statistics), normally inside or after room.onPlayerJoin, and call it again whenever that ELO changes. The player must use their current HaxBall player ID as gameId.

What happens: The local ELO snapshot is updated and immediately sent to connected BOLT clients. Future BOLT clients receive the latest snapshot when they connect. The ELO is display-only and is not stored by BOLT or added to the official leaderboard. Invalid values are ignored, decimals are truncated, and the entry is removed automatically when that player leaves.

setElos([{ gameId, elo }])

When: Call it when you load or recalculate ELO for the whole current roster. It is useful after room startup, a database refresh, or a batch ELO update. Pass every ELO that should remain visible.

What happens: The existing local list is replaced, not merged, and one complete snapshot is sent to BOLT clients. Any player omitted from the array loses their displayed room ELO. Invalid entries are skipped. An empty array clears every room ELO.

elos()

When: Call it whenever your script needs to inspect the ELO values currently held by the partner runtime. It is synchronous and does not contact the platform.

What happens: It returns a new array in the form [{ gameId, elo }]. Changing the returned array does not change the stored values; use setElo or setElos to make changes.

setAfkPlayers(playerIds)

When: Call it whenever you want to update the list of players marked as AFK. Pass an array of player game IDs (e.g. [3, 8]).

What happens: Sends the AFK snapshot directly to connected BOLT clients to display the AFK badge in the room menu.

setBotPlayers(botIds)

When: Call it whenever you manage custom bots and want to update the list of bot player IDs (e.g. [20]).

What happens: Connected BOLT clients display the bot badge and bot UI controls for those player IDs.

setCaptainPick(pick)

When: Call it whenever your room starts, changes, or ends a captain pick (null ends it). Your room runs the pick; BOLT only shows it.

room.bolt.setCaptainPick({
  captainId: 3,
  team: 1,                    // defaults to the captain's team
  candidateIds: [7, 8, 9],    // chat numbers 1..N name these
  count: 1,                   // how many the captain still needs
  endsAt: Date.now() + 20000, // omit for an untimed pick
  shortcuts: ['top', 'random'],
  allowReturn: false,         // may the captain drag teammates back?
});

room.bolt.onCaptainPick((captainId, choice) => {
  // choice: a candidate id, or an offered shortcut. Move the players yourself.
});

What happens: BOLT clients show the pick banner, countdown, numbered candidates and the shortcut buttons you offered. The captain's clicks, drags and chat choices (2, top) reach onCaptainPick only when they are valid. onCaptainReturn(captainId, playerId) receives teammate returns when allowReturn is set.

setVoteState(options)

When: Call it to open, update, or close a custom vote-kick or moderation vote.

room.bolt.setVoteState({
  vote: {
    targetName: "Player",
    reason: null,
    yes: 2,
    need: 3,
    endsAt: Date.now() + 30000,
  },
});

Broadcasting an outcome closes the current vote and notifies the players who are connected at that moment:

room.bolt.sendVoteOutcome({
  type: "failed",
  targetName: "Player",
  yes: 2,
  need: 3,
});

sendVoteOutcome(outcome)

When: Call it to close the current vote and notify only players currently connected. Vote outcomes are not replayed to players who join later.

setMatchState(options)

When: Call it to notify connected clients whether the current match is rated (e.g. room.bolt.setMatchState(true) or room.bolt.setMatchState({ rated: true })).

goal(goal) and save(save)

When: Available only when you run your own statistics, with bolt: { statistics: { read } }. Call goal once per goal, from onTeamGoal; call save when a player makes a save.

What happens: goal announces the oldest goal that has not been announced yet. Connected BOLT clients show the goal text ("XXXX SCORED", "ASSISTED BY YYYY") from what you announce, and the player totals for goals and assists update. Everything else about the goal (the explosion, the sound, the scoreboard) happens immediately, as always; only the text waits for your announcement. If you never announce a goal, BOLT clients show no goal text for it.

goal takes scorerId and assisterId (both optional) and ownGoal:

room.onTeamGoal = (team) => {
  const { scorerId, assisterId } = myGoalDetector.lastGoal();
  room.bolt.goal({ scorerId, assisterId });      // "ANA SCORED", "ASSISTED BY BIA"
  // room.bolt.goal();                           // "RED SCORED" (no player)
  // room.bolt.goal({ scorerId, ownGoal: true }); // "RED SCORED", "OWN GOAL BY ANA"
};
  • scorerId is the player who put the ball in. Leave it out and clients show "RED SCORED" or "BLUE SCORED".
  • With ownGoal: true, scorerId is a player on the team that conceded. The goal is credited to the other team and to no player's goal total.
  • assisterId needs a scorerId, cannot equal it, cannot be combined with ownGoal, and must be on the team that scored.
  • goal throws when the players do not match the team that scored, when an id is not a player on a team, or when there is no goal waiting. A call that throws announces nothing and the goal stays waiting.

save({ playerId }) adds a save for that player. It reaches the totals with the next statistics update, within about a second.

bolt.statistics.read()

When: Pass it as bolt: { statistics: { read } } to run your own statistics. BOLT calls read() about once a second while a match is running, and at the final whistle, and sends the result only when it changed. You never push statistics yourself, so calling anything more or less often cannot flood the room. Keep read cheap.

read() returns the figures BOLT cannot see from goals and saves. Everything is optional and missing values read as zero:

const room = BOLTInit({
  roomName: "My room",
  bolt: {
    statistics: {
      read: () => ({
        redPossessionPercentTenths: 640,   // 64.0%
        bluePossessionPercentTenths: 360,
        players: {
          3: {                              // keyed by player id
            completedPasses: 12,
            possessionPercentTenths: 310,
            passingAccuracyPercentTenths: 850,
            performanceRatingTenths: 78,    // 7.8
            mvpAwarded: false,
          },
        },
        // ballHeatmap, expectedGoals: optional
      }),
    },
  },
});

BOLT fills in each player's name, country, team and bot flag from the room, and adds the goals, assists and saves you announced. A match starts from zero. If read() throws or returns something invalid, the last good figures stay up and the problem is logged once per match.

sendEloUpdate(update)

When: Call it after a match concludes to broadcast the post-match ELO change.

room.bolt.sendEloUpdate({
  matchPublicId: "match-123",
  redScore: 3,
  blueScore: 1,
  before: 1500,
  after: 1515,
  delta: 15,
});

onCommand(handler)

When: Register the handler immediately after initialization when your script needs to react to BOLT room-menu actions. Keep the returned cleanup function and call it when your feature is disabled or replaced. You do not need this listener only to use BOLT's built-in features.

What happens: The handler runs with the sending player's HaxBall ID and a validated command. Enabled built-in features process the command first, then your handlers run in registration order. Removing the listener stops future callbacks but does not undo actions already applied. All listeners disappear when the hosting page is closed or refreshed.

const stopListening = room.bolt.onCommand((playerId, command) => {
  console.log(playerId, command);
});

// Later:
stopListening();

Commands received by onCommand

The first argument is the HaxBall player ID that sent the command. The second argument has one of these shapes:

{ type: "afk.set", afk: true | false }

{ type: "bot.add" }
{ type: "bot.remove", playerId: 4 }

{ type: "captain.pick", choice: 7 | "top" | "bottom" | "random" }
{ type: "captain.move", playerId: 7, team: 0 | 1 | 2 }

{ type: "vote.open", targetId: 7, reason: "reason" | null }
{ type: "vote.cast", choice: "yes" | "no" }

Presentation methods summary

Use presentation methods only when your script owns the corresponding feature. Disable the matching built-in feature in BOLTInit first so two implementations do not publish competing state.

room.bolt.setAfkPlayers([3, 8]);
room.bolt.setBotPlayers([20]);
room.bolt.setMatchState({ rated: true });

The presentation methods directly update the connected BOLT clients over the room's optional peer channel without mutating game physics. HaxBall clients ignore this optional channel and continue playing normally.

Standard HaxBall listeners are unchanged

Continue using room.onPlayerJoin, room.onPlayerLeave, room.onGameTick, and every other standard headless callback normally. BOLTInit does not replace their public signatures. room.bolt.onCommand is the only additional listener API.

Running in Node.js (boltgame.js)

When running in Node.js 24 or newer, use boltgame.js as the server-side replacement for haxball.js. It uses native WebRTC and does not require Chromium or an open BOLT Headless browser page. Change the package import; standard room configuration, callbacks, and room methods remain the same.

Installation

npm install boltgame.js

Usage

Use the exact same syntax as haxball.js:

import BoltGameJS from 'boltgame.js';

const HBInit = await BoltGameJS();

const room = HBInit({
  roomName: "My BOLT Room",
  maxPlayers: 12,
  public: true,
  noPlayer: true
});

Or configure BOLT features with BOLTInit:

import { BOLTInit } from 'boltgame.js';

const room = BOLTInit({
  roomName: "BOLT Pro Room",
  bolt: {
    statistics: 'builtin',
    voteKick: true,
    afk: true,
    bots: true,
    eloLabel: "ROOM ELO"
  }
});

To list an existing production room on both BOLT and HaxBall while retaining all room-owned policy, pass a fresh HaxBall token and disable every built-in feature explicitly:

import { BOLTInit } from 'boltgame.js';

const room = BOLTInit({
  roomName: "My Production Room",
  maxPlayers: 16,
  public: true,
  noPlayer: true,
  token: process.env.HAXBALL_TOKEN,
  bolt: {
    afk: false,
    bots: false,
    voteKick: false,
    statistics: 'off'
  }
});

This creates one room process, not separate BOLT and HaxBall rooms. The token publishes that host upstream to HaxBall and BOLT exposes the same live room. room.bolt remains available for optional display-only ELO and custom UI state. BOLT does not take ownership of the room's AFK, captain, moderation, statistics, ELO, level, or persistence systems.

Gameplay packets remain direct WebRTC traffic between each player and the room process on the owner's VPS. BOLT handles directory and signaling only; it does not relay gameplay. The optional bolt presentation channel is direct to the same host as well, so dual listing introduces no BOLT gameplay hop. Exact latency can still differ by the client's normal ICE/network route.

See the package on npm: https://www.npmjs.com/package/boltgame.js.