connect() function
@irtio/client 5.0BrowsersNodeThe connect() function connects to the room at a room URL and resolves with a RoomClient once the client holds the room’s full state. It takes a URL and an init object, as fetch() takes a URL and a RequestInit.
Syntax
connect(input)
connect(input, init)
Parameters
input- A string or a
URL: the room URL, such as"https://rooms.irt.io/my-game/main", or one relative to the project URL, such as"main". A relative URL resolves asnew URL(input, projectUrl)does.ws:andwss:URLs name the same rooms ashttp:andhttps:. initOptional-
An object with any of these properties:
project- A string or a
URL: the project URL a relative room URL resolves against, such as"https://rooms.irt.io/my-game/". Defaults to the page’sirt-projectmeta tag. type- A string: the room type the client expects, the one whose schema
schemais. A connection that creates its room creates it of this type. Defaults to"default". token- A string: a player token from your backend. Without one, the client joins as a guest; see Guests.
guest- A string: where a guest’s token is kept.
"tab"keeps it insessionStorage, so each tab is its own player, and"browser"keeps it inlocalStorage, so every tab of the browser is one player. Unused with atoken. Defaults to"tab". schema- A
Schema: whatdefineSchema()returns, from the same module the room uses. It typesroom.state,room.privateandroom.calls. Defaults to the empty schema. timeout- A number: the milliseconds the first connection may take to become ready, waking included. Defaults to 15000.
signal- An
AbortSignalthat aborts connecting. It has no effect once the client is ready; callclose()then instead. targets- An object whose keys are room types and whose values are their schemas: the room types a handoff may take the player to. A type left out gets the empty schema. See Lobbies and parties.
initcan also be aDevConnectInitfrom@irtio/client/dev, which adds development hooks to these properties:dial- A function that opens the transport, called with the room URL on every connect and reconnect, as
dialWebSocket()describes.simulateNetwork()returns one. Defaults to WebTransport, then WebSocket. fetch- A function that replaces the global
fetch()for the client’s player data, collection and leaderboard requests, for tests.@irtio/testingpasses one. Defaults to the globalfetch(). clock- An object with
now(),setTimeout()andclearTimeout()methods: the clock and timers the client runs on, for tests.@irtio/testingpasses one. Defaults toperformance.now()and the platform’s timers.
Return value
A Promise that resolves with the RoomClient, typed as a ReadyRoomClient: the same client with state and private typed as set, since it has been ready.
Exceptions
TypeError- Rejects with this if
inputis relative and there’s no project URL to resolve it against; if its path doesn’t end in a project and a room ID; or if it, or the project URL, isn’t anhttp:,https:,ws:orwss:URL. IrtError- Rejects with this if the client doesn’t become ready. Its
nameisNetworkError, with code 0, if neither WebTransport nor WebSocket reached the room, or if the runtime has no globalWebSocket, as in Node before 24. It’s named for the close code, with that code as itscode, if the router closes with a code the client doesn’t reconnect after, such as aVersionErrorfor 4004. It’s aTimeoutError, with code 0, iftimeoutpasses first, and anAbortError, with code 0, ifsignalaborts. See Errors and close codes.
Description
connect() resolves after the room is running and the client holds its full state, so room.state and room.private are set. After that, the client reconnects by itself whenever the connection drops with a code that allows it, and fires a reconnecting event and an open event as it does.
connect(input, init) is new RoomClient(input, init).ready. The room’s waking event fires before connect() resolves, so to show that a room is starting, construct the RoomClient, add the listener and await its ready.
timeout counts waking, which a caller can’t see. An AbortSignal.timeout(ms) as the signal works too.
A room of another type than type, or a type the live build doesn’t have, closes the connection with 4015, which reloading doesn’t fix; its reason names the room’s type. Pass type for every room that isn’t of the default type when you connect to it by URL, such as one createRoom({ type }) made. A handoff’s own client already has it.
Transports
The client connects with WebTransport at the room URL itself, with one bidirectional stream for reliable messages and datagrams for unreliable ones. If WebTransport isn’t available or doesn’t connect within 3 seconds, the client uses WebSocket at the room URL, with wss: for https:, and stays on WebSocket for later reconnects. Node has no WebTransport, so it uses WebSocket.
Guests
Without a token, the router mints a guest token with a player ID of guest:<random>. The client keeps it in sessionStorage under irt.guest.<project>, <project> being the project’s slug, and sends it on every connect, so each tab is its own guest: it keeps its player ID across reconnects and reloads of that tab, and a new tab is a new player. Where there’s no sessionStorage or it’s blocked, the token is kept in memory. The token lasts 30 days, and the router renews it on each connect.
With guest: "browser", the token is kept in localStorage under the same key, so every tab of the browser is one guest, across browser restarts too. Two clients that are the same player can’t be in one room: the router closes the older with 4012. See Games without a backend.
Examples
Joining a table with its schema
The client passes the schema the room uses, so room.state is typed, and reloads for the new build when the room refuses an older page.
// join-table.ts
import { connect, defineSchema, entity, IrtError, reloadForNewBuild } from "@irtio/client";
const Table = entity("table", { round: "u16" });
const schema = defineSchema({ state: Table });
try {
const room = await connect("main", { schema, timeout: 20_000 });
console.log(`round ${room.state.round}`);
} catch (e) {
if (e instanceof IrtError && e.name === "VersionError") reloadForNewBuild();
else throw e;
}
Cancelling a join
A cancel button on the loading screen aborts connecting, and the client rejects with an AbortError.
// cancel-join.ts
import { connect, IrtError } from "@irtio/client";
const joining = new AbortController();
document.querySelector("#cancel")?.addEventListener("click", () => joining.abort());
try {
const room = await connect("lobby", { signal: joining.signal });
console.log(`joined as ${room.player}`);
} catch (e) {
if (e instanceof IrtError && e.name === "AbortError") console.log("back to the menu");
else throw e;
}
Connecting to a room of another type
A match room isn’t of the default type, so the client says which type it expects, with that type’s schema.
// join-match.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Match = entity("match", { round: "u8" });
const matchSchema = defineSchema({ state: Match });
export async function joinMatch(url: string) {
const match = await connect(url, { type: "match", schema: matchSchema });
console.log(`round ${match.state.round} of ${match.id}`);
return match;
}
See also
RoomClientcreateRoom(), for a room URL to connect to- Errors and close codes, for every way it rejects
- Node clients and bots
- Games without a backend
Runtime availability
| Browsers | Node | |
|---|---|---|
connect() | 5.0 | 5.0 |