# connect() function

> The connect() function connects to a room and resolves with its client once the client holds the room's full state.

The **`connect()`** function connects to the room at a room URL and resolves with a [`RoomClient`](/docs/client/room-client) 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

```ts
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 as `new URL(input, projectUrl)` does. `ws:` and `wss:` URLs name the same rooms as `http:` and `https:`.

`init` Optional
: 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's `irt-project` meta tag.

  `type`
  : A string: the [room type](/docs/guides/concepts#rooms) the client expects, the one whose schema `schema` is. 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](#guests).

  `guest`
  : A string: where a guest's token is kept. `"tab"` keeps it in `sessionStorage`, so each tab is its own player, and `"browser"` keeps it in `localStorage`, so every tab of the browser is one player. Unused with a `token`. Defaults to `"tab"`.

  `schema`
  : A [`Schema`](/docs/room/schema): what `defineSchema()` returns, from the same module the room uses. It types `room.state`, `room.private` and `room.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 `AbortSignal` that aborts connecting. It has no effect once the client is ready; call [`close()`](/docs/client/room-client/close) 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](/docs/room/guides/lobbies).

  `init` can also be a `DevConnectInit` from `@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()`](/docs/client/dialwebsocket) describes. [`simulateNetwork()`](/docs/client/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/testing` passes one. Defaults to the global `fetch()`.

  `clock`
  : An object with `now()`, `setTimeout()` and `clearTimeout()` methods: the clock and timers the client runs on, for tests. `@irtio/testing` passes one. Defaults to `performance.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 `input` is 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 an `http:`, `https:`, `ws:` or `wss:` URL.

[`IrtError`](/docs/client/irt-error)
: Rejects with this if the client doesn't become ready. Its `name` is `NetworkError`, with code 0, if neither WebTransport nor WebSocket reached the room, or if the runtime has no global `WebSocket`, as in Node before 24. It's named for the close code, with that code as its `code`, if the router closes with a code the client doesn't reconnect after, such as a `VersionError` for 4004. It's a `TimeoutError`, with code 0, if `timeout` passes first, and an `AbortError`, with code 0, if `signal` aborts. See [Errors and close codes](/docs/client/errors#connect).

## 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](/docs/client/room-client/reconnecting-event) and an [`open` event](/docs/client/room-client/open-event) as it does.

`connect(input, init)` is `new RoomClient(input, init).ready`. The room's [`waking` event](/docs/client/room-client/waking-event) fires before `connect()` resolves, so to show that a room is starting, construct the `RoomClient`, add the listener and await its [`ready`](/docs/client/room-client/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](/docs/guides/no-backend#guests).

## 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.

```ts
// 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`.

```ts
// 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.

```ts
// 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

- [`RoomClient`](/docs/client/room-client)
- [`createRoom()`](/docs/client/createroom), for a room URL to connect to
- [Errors and close codes](/docs/client/errors#connect), for every way it rejects
- [Node clients and bots](/docs/client/guides/node)
- [Games without a backend](/docs/guides/no-backend)
