Skip to content

Get started

Node.js quickstart

Install the SDK and host your first public room from Node.js.

Prerequisites

  • Node.js 24 or newer
  • A Ball2D API key

Install

Create a project and add the SDK.

npm install ball2d

Write the host

This room lists itself publicly, puts every new player on the smaller team and starts a match as soon as two players are on the pitch.

host.mjs
import { createRoom } from 'ball2d/node';

const apiKey = process.env.BALL2D_API_KEY;
if (!apiKey) throw new Error('Set BALL2D_API_KEY');

const room = await createRoom({
  apiKey,
  roomName: 'Evening football',
  noPlayer: true,
  maxPlayers: 12,
  public: true,
});

room.onError = (message) =>
  console.error('Room error:', message);

room.onPlayerJoin = async (player) => {
  const players = room.getPlayerList();
  const red = players.filter((p) => p.team === 1).length;
  const blue = players.filter((p) => p.team === 2).length;
  await room.setPlayerTeam(
    player.id,
    red <= blue ? 1 : 2,
  );
  await room.sendAnnouncement(
    `Welcome, ${player.name}!`,
    player.id,
  );

  const fielded = room
    .getPlayerList()
    .filter((p) => p.team !== 0).length;
  if (fielded >= 2 && room.getScores() === null)
    await room.startGame();
};

await room.setDefaultStadium('Classic');
await room.setScoreLimit(3);
await room.setTimeLimit(5);

console.log(`Room open: ${room.roomLink}`);

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    room.close();
    await room.closed;
    process.exit(0);
  });
}

Run it

Terminal
BALL2D_API_KEY="b2d_…" node host.mjs

Open the printed link, or find Evening football in the room list on ball2d.com. Press Ctrl + C to close the room.

noPlayer: true runs the room entirely from code. Leave it out and your process joins as player 0, an admin named Host, which can chat with sendChat().

Next steps