joinByCode() function

Available since @irtio/client 5.0BrowsersNode

The joinByCode() function resolves with the URL of the room a join code names, to pass to connect().

Syntax

joinByCode(code)
joinByCode(code, init)

Parameters

code
A string: the join code, 6 characters of A-H, J-N, P-Z and 2-9. It’s case-insensitive and spaces around it are ignored, so "k7qx2m " finds K7QX2M.
init Optional

An object with any of these properties:

project
A string or a URL: the project URL, such as "https://rooms.irt.io/my-game/". Defaults to the page’s irt-project meta tag.
token
A string: a player token. Guests leave it out.
signal
An AbortSignal that aborts the request.

Return value

A Promise that resolves with the room’s URL, a string.

Exceptions

TypeError
Rejects with this if there’s no project URL, no project given and no irt-project meta tag; if the project URL’s path doesn’t end in a project; or if it isn’t an http:, https:, ws: or wss: URL.
IrtError
Rejects with this if the router refuses the request, with the HTTP status as its code: 404, a NotFoundError, when no room has the code, its room was deleted or the project doesn’t exist; 403, a NotAllowedError, when the project’s players.createRooms is off; 401 for an invalid token; and 429, a QuotaExceededError, when the address is rate limited. If the request didn’t complete, its code is 0 and its name is TimeoutError when signal came from AbortSignal.timeout() and aborted, AbortError when another signal aborted, with its reason as cause, and NetworkError otherwise, with the failed fetch()’s error as cause.

Description

A room gets a join code when createRoom() asks for one with joinCode: true. The code lasts as long as its room. Room code reads it as room.joinCode, such as to show it in the lobby.

Examples

Joining a friend’s game

The player types the code their friend shared. A code no room has gets a message rather than an error.

// join-friend.ts
import { connect, IrtError, joinByCode } from "@irtio/client";

export async function joinFriend(code: string) {
  try {
    return await connect(await joinByCode(code));
  } catch (e) {
    if (e instanceof IrtError && e.name === "NotFoundError") {
      console.warn(`no game has the code ${code.trim().toUpperCase()}`);
      return undefined;
    }
    throw e;
  }
}

connect() rejects with a NotFoundError too, for close code 4002, if the room is deleted between the two calls.

See also

Runtime availability

BrowsersNode
joinByCode()5.05.0