---
title: Use WebSockets
description: Declare WebSockets in the manifest, accept the upgrade in your server, connect from a page or a native app, and reconnect after a close.
slug: /guides/use-websockets
order: 6
visibility: public
redirects_from: []
---

# Use WebSockets

Prompt:

> Show new chat messages to everyone in the room as soon as they are sent.

Also works:

- "Add live updates to the dashboard over a WebSocket."
- "Why does my socket keep closing on the hosted app?"

Declare `websockets` in the manifest ([step 1](#1-declare-websockets-in-the-manifest)), and accept the upgrade on the server's own port ([step 2](#2-accept-the-upgrade-in-the-server)). The page then connects to the same hostname with `wss://` ([step 3](#3-connect-from-the-app-s-page-or-list-another-origin)), and reconnects after a close ([step 5](#5-reconnect-after-a-close)).

## What your AI tool does

- Adds the `websockets` member to the [manifest](/cloud/concepts/glossary/#manifest) and submits the whole manifest with `submit_manifest`.
- Writes one server that answers requests and accepts the upgrade on the same port, with the `ws` library, and pings each connection every 30 seconds.
- Writes the page's client, which reconnects after a close with a growing wait.
- Deploys, and [promotes](/cloud/concepts/glossary/#promote) if the application has a development environment.
- Tests the connection on your machine, then on the hosted hostname, and reads a refused upgrade's `error` and `detail` with `curl`.
- Asks you nothing unless a page on another address opens the connection; then it asks for that page's origin before it submits the manifest. No step needs a browser approval.

## What you need

- An application that deploys ([Deploy from your computer](/cloud/getting-started/deploy-an-application/)).
- A server built on Node.js's `http` module, directly or through a framework such as Express, so the WebSocket library can take the upgrade from it.

## Before your AI starts

**For the AI tool:** Check the following before starting.

- Your AI tool connected and signed in ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)).
- `list_applications` returns the application's identifier and each environment's `grain`. Both Shared 0.5 GB and Shared 1 GB support WebSockets, on shared compute and in their own container.
- The application's current manifest, because a submission replaces the whole document.
- `ws` among the application's dependencies, installed before the build.

## Steps

### 1. Declare WebSockets in the manifest

An application accepts WebSocket upgrades only once its manifest declares the `websockets` member. Without it, every upgrade is refused 400 `websockets_not_declared` before it reaches the application. The member is an object holding at most `origins`. The empty object admits a page served from the application's own hostname, and a client outside a browser, such as a native app or a script.

```json
"websockets": {}
```

The declaration takes effect when `submit_manifest` records it, in both environments, with no deploy: the [serving router](/cloud/concepts/glossary/#serving-router) reads it within about 30 seconds. Removing the member, or an origin, closes the open connections it admitted with code 1008 within about the same time. A page on another address needs its origin listed, as step 3 says. [The manifest](/cloud/concepts/the-manifest/) lists every member.

### 2. Accept the upgrade in the server

The upgrade reaches the application's own server, on the port its requests use. Hand that server to the WebSocket library, so one process serves both. This `server.mjs` answers the manifest's `health` path, here `/health`, and accepts connections on `/live`. It sends each message to every open connection, and pings each connection every 30 seconds, so the router's idle limit never closes a quiet one (step 4).

The server admits anyone who connects, a script with no session among them, and there is no per-message charge. For a room of signed-in users, [step 6](#6-sign-in-on-the-connection) says how to turn away a connection with no verified user.

```js
import http from 'node:http';
import { WebSocketServer } from 'ws';

const server = http.createServer((req, res) => {
  if (req.url === '/health') {
    res.writeHead(200, { 'content-type': 'text/plain' });
    res.end('ok');
    return;
  }
  res.writeHead(404, { 'content-type': 'text/plain' });
  res.end('not found');
});

const sockets = new WebSocketServer({ server, path: '/live' });

sockets.on('connection', (socket) => {
  socket.on('message', (data) => {
    for (const other of sockets.clients) other.send(data.toString());
  });
});

const heartbeat = setInterval(() => {
  for (const socket of sockets.clients) socket.ping();
}, 30_000);
server.on('close', () => clearInterval(heartbeat));

server.listen(process.env.PORT ?? 8080);
```

With Express, pass the app to `http.createServer(app)` in place of the handler above.

Socket.IO attaches to the same `http` server in the same way, and serves its own path, `/socket.io/`. Socket.IO sends its own heartbeat as a data message every 25 seconds. Its client also starts on HTTP long-polling, and each poll is a request. So prefer `ws`. With Socket.IO, set `transports: ['websocket']` on the client and leave out step 4's ping.

Use a path of the application's own. An upgrade under `/__account/`, `/__router/`, or `/.well-known/` is refused 400 `upgrade_not_served`, because the platform answers those paths itself. An upgrade on `/` reaches the application, even where the platform serves the web client's page there for an ordinary request.

The upgrade request meets every check an ordinary request meets, the per-address limits and the sign-in gate among them ([Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/)). A handshake carries no body: one with a body is refused 400 `invalid_request`. The connection opens only when the server answers 101. Any other answer, such as the one the library writes for a path it does not serve, reaches the client as an answer, and the connection closes. The platform's refusals carry a JSON body with `error`; the library's own answer does not.

Once the server answers 101, the request deadline no longer applies, and the connection stays open within the limits in [Limits and metering](#limits-and-metering).

Each environment runs one copy of the server, so one process holds every connection to that environment, and the loop above reaches every client. A deploy, promote, rollback, or restart starts a new copy and closes the old copy's connections (step 5).

### 3. Connect from the app's page, or list another origin

A page served from the application's hostname connects to the same hostname with `wss://`. This script shows each message in a list with the id `messages`, and sends what the person types in the `text` input of a form with the id `send`. It reconnects after a close as step 5 describes.

```js
const list = document.querySelector('#messages');
const form = document.querySelector('#send');
const STOP = new Set(['account suspended', 'account paused']);
let socket;
let wait = 1_000;

function show(text) {
  const item = document.createElement('li');
  item.textContent = text;
  list.append(item);
}

function connect() {
  socket = new WebSocket(`wss://${location.host}/live`);
  socket.onopen = () => { wait = 1_000; };
  socket.onmessage = (event) => show(event.data);
  socket.onclose = (event) => {
    if (event.code === 1008 && STOP.has(event.reason)) {
      show(`Live updates stopped: ${event.reason}.`);
      return;
    }
    const delay = event.code === 1001 ? Math.random() * 1_000 : wait + Math.random() * 1_000;
    if (event.code !== 1001) wait = Math.min(wait * 2, 60_000);
    setTimeout(connect, delay);
  };
}

form.addEventListener('submit', (event) => {
  event.preventDefault();
  if (socket.readyState === WebSocket.OPEN) socket.send(form.elements.text.value);
  form.reset();
});

connect();
```

Every browser sends an `Origin` header on the handshake, the address of the page that opens the connection. The router admits `https://` with the hostname the upgrade arrived on, and each origin the declaration lists. Any other origin is refused 403 `origin_not_admitted`, before the router reads the visitor's session. So a page on another site cannot open a connection that carries your visitor's sign-in cookie. A client that sends no `Origin`, such as a native app or a script, is admitted.

List an origin only when a page on another address opens the connection, such as a web client hosted elsewhere. Only `https://` origins can be listed. A page served from `http://localhost` cannot connect to a hosted hostname, so run the server on your machine too (step 7).

`origins` holds at most ten. Each is exact: `https://`, a lowercase hostname, and a port only when it is not 443, with no path, no wildcard, and no repeat. Write an origin on port 443 without a port, since `:443` is refused, and keep each dot-separated part of its hostname to 63 characters and the whole hostname to 253. A test checks this sample against the platform's rule for origins.

```json
"websockets": { "origins": ["https://app.example.com", "https://staging.example.com:8443"] }
```

A submission whose list breaks a rule is refused 400 `manifest_invalid`. Each line of its `violations` gives the entry's path and the rule, such as `/websockets/origins/1: must omit the default port`.

The router checks the handshake's origin before it reads the declaration. A page on another site sees 403 `origin_not_admitted` before `websockets_not_declared`, so a 403 does not mean the declaration is in place.

### 4. Keep the connection open

An open WebSocket connection keeps production awake as a request in flight does, so the idle stop does not close it.

The router closes a connection after 120 seconds with no byte in either direction, with code 1001. So the server sends a WebSocket ping at least every 60 seconds; step 2's server sends one every 30. Every browser and WebSocket client answers a ping with a pong by itself. There is no per-message charge.

A connection also closes two hours after it opened, with code 1001, whatever it carries. It can also close unexpectedly with code 1006 and no reason. In each case the client reconnects, as step 5 describes.

### 5. Reconnect after a close

The router closes a connection with a code and a short reason, and the client reconnects. The code tells the client how soon:

| Code | Reasons | What happened | What the client does |
| --- | --- | --- | --- |
| 1001 | `idle bound`, `lifetime bound` | No byte moved for 120 seconds, or the connection reached two hours. | Reconnects after a random wait of up to a second. |
| 1012 | `compute replaced`, `router stopping` | A deploy, promote, rollback, or restart replaced the copy of the server, or the router replica stopped. | Reconnects after a random wait of up to a few seconds, so its clients do not all return at the same moment. |
| 1013 | `standing stale` | `standing stale` means the platform could not confirm for a while that the account is in good standing, because the router could not reach the platform's records. Its requests are refused the same way until it can. | Reconnects with a growing wait. |
| 1008 | The table below | The connection passed a limit, its sign-in was revoked, or a request on the environment would now be refused. | Reads the reason, and reconnects with a growing wait when the cause can pass. |

A connection can also end without a close frame, which a browser reports as code 1006. A network fault does this, and so does the server ending the connection itself. It also happens when the router cannot send its close between two frames within one second. The client reconnects with a growing wait.

For a growing wait, wait about one second before the first attempt, double the wait after each failed attempt up to about a minute, and add a random part to each wait. Stop reconnecting on `account suspended` and `account paused`, which last until the account or the month changes, and tell the user. Step 3's client does all of this.

The reasons a 1008 close carries:

| Reason | Cause |
| --- | --- |
| `message bound` | The connection passed its data-message limit for the minute ([Limits and metering](#limits-and-metering)). |
| `source message bound` | The client's address passed its data-message limit for connections without a session. |
| `user message bound` | The signed-in user passed their data-message limit, whatever addresses they came from. |
| `signed-in source message bound` | The client's address passed its data-message limit for connections with sessions. |
| `frame bound` | The connection passed its limit of frames of every kind for the minute. |
| `account paused` | The application's account used its balance for the month, pausing the application and closing its open connections. The pause ends at the first instant of the next UTC month. Earlier reconnects receive 429 `account_paused`, with `Retry-After` giving the seconds left; a growing wait gains nothing until then. |
| `account suspended` | The account was suspended. |
| `environment halted` | The environment was halted. |
| `not deployed` | The environment no longer runs a version. |
| `application gone` | The hostname no longer names a live application, after a deletion or a rename. |
| `target unreadable` | The router could not read where the environment runs. |
| `websockets withdrawn` | The manifest no longer declares `websockets`. |
| `origin not admitted` | The manifest no longer lists the origin of the page that opened the connection. |
| `sign-in required` | The audience became `invited` or `workforce`, or the connection's path left `session_free_paths`, and the connection holds no valid session. |
| `session revoked` | The session ended, by a sign-out or a revocation. |
| `user revoked` | `set_end_user_standing` suspended the end user, which ends every session signed before. |
| `realm revoked` | The platform revoked every session of the [realm](/cloud/concepts/glossary/#realm). |
| `key revoked` | `revoke_app_sign_in_keys` revoked the key that signed the session. |
| `realm unknown` | The router no longer finds the realm the session belongs to. |
| `session unchecked` | The router could no longer keep the realm's revocations current, so it closed the connection rather than keep it unchecked. |

### 6. Sign in on the connection

A page on the application's hostname sends the session cookie with the handshake, as it does with a request. The router verifies the session at the handshake and sets the header `x-turnzero-cloud-session` on the upgrade request. So the server tells which user opened the connection as [Tell which user sent a request](/cloud/guides/add-sign-in-to-your-app/#3-tell-which-user-sent-a-request) shows for a request, reading the upgrade request the `connection` event passes as its second argument. An expired cookie token is issued again on the 101, as on any response.

Where the room is for signed-in users, close a connection whose request carries no verified user, and handle no message from it.

A native app sends its [bearer token](/cloud/concepts/glossary/#bearer-token) in the handshake's `Authorization` header, when its WebSocket client lets it set headers. A browser's `WebSocket` cannot, so a page relies on the cookie. An expired or revoked bearer token is refused 401 `authentication_required` on every audience, so refresh it before reconnecting.

The router reads the session once, at the handshake. Revoking the session, the user, the realm's sessions, or the key that signed the session closes the connection with code 1008 within about 60 seconds. The token's expiry alone does not close an open connection, and the two-hour limit still applies.

Under an `invited` or `workforce` [audience](/cloud/concepts/glossary/#audience), an upgrade without a valid session is refused 401 `authentication_required`, never sent to the sign-in page, because a handshake is no page visit. A path listed in `session_free_paths` is admitted without one.

### 7. Deploy and test

Test on your machine first. Run the server as [Run your app on your computer](/cloud/guides/run-your-application-on-your-machine/) describes, and connect to `ws://localhost:<port>/live` at the command's printed port. The platform's checks and limits do not apply there.

With `turnzero` 0.38.0 or later and `--sign-in <hostname>`, sign in through the local browser page first; its cookie then reaches the local WebSocket upgrade too. Without `--sign-in`, hand your test a hosted session instead. [Test a local run](/cloud/guides/test-sign-in-with-test-end-users/#7-test-a-local-run) describes the sign-in and its browser and session limits.

Then deploy, and promote if the application has a development environment. Both Shared 0.5 GB and Shared 1 GB serve WebSocket upgrades in production and development. This includes shared compute (`pod`) and environments in their own container (`container`). `list_applications` and `read_status` show each environment's `grain` ([Grain and development group](/cloud/concepts/glossary/#grain-and-development-group)).

A refused upgrade answers with a status and a JSON body whose `error` names the refusal and whose `detail` says why, and the connection then closes. A browser's `WebSocket` does not show the answer, and reports a close with code 1006. Read the answer with a client outside the browser, such as `curl`, giving the application's hostname and the path.

```text
curl --http1.1 --include -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" https://<label>.ai.host/live
```

A refusal prints its status line and its JSON body. A served upgrade prints `HTTP/1.1 101 Switching Protocols` and then waits on the open connection; stop it with Ctrl+C.

## Limits and metering

Connection limits apply separately on each router replica. A client cannot choose its replica, so it may reach a full replica while another still has room.

| Limit | Figure | Past it |
| --- | --- | --- |
| Time with no byte in either direction | 120 seconds | Closed with code 1001 |
| Time open | Two hours | Closed with code 1001 |
| Connections to one environment, on each router replica | Shared 0.5 GB: 200; Shared 1 GB: 500 | Upgrade refused 429 `socket_limit_reached` |
| Connections from one client address without a session, to one application, on each router replica | 50, and at most half the environment's figure | Upgrade refused 429 `socket_limit_reached` |
| Connections under one signed-in user, to one application, on each router replica | 50, and at most half the environment's figure | Upgrade refused 429 `socket_limit_reached` |
| Connections from one client address with sessions, to one application, on each router replica | 500, and at most half the environment's figure | Upgrade refused 429 `socket_limit_reached` |
| Connections from one client address without a session, across every application, on each router replica | 200 | Upgrade refused 429 `socket_limit_reached` |
| Connections from one client address with sessions, across every application, on each router replica | 500 | Upgrade refused 429 `socket_limit_reached` |
| Connections across every application, on each router replica | 8,000 | Upgrade refused 429 `socket_limit_reached` |
| Data messages a client sends on one connection | 600 in a UTC minute | Closed with code 1008, `message bound` |
| Data messages one client address sends one application without a session, across its connections on one router replica | 600 in a UTC minute | Closed with code 1008, `source message bound` |
| Data messages one signed-in user sends one application, across the user's connections on one router replica | 600 in a UTC minute | Closed with code 1008, `user message bound` |
| Data messages one client address sends one application with sessions, across its connections on one router replica | 60,000 in a UTC minute | Closed with code 1008, `signed-in source message bound` |
| Frames of every kind a client sends on one connection | 6,000 in a UTC minute | Closed with code 1008, `frame bound` |

Half the environment's figure is 100 on Shared 0.5 GB and 250 on Shared 1 GB. The lower per-address or per-user bound in the table still applies. When a count is reached, `socket_limit_reached` gives the limit and says that it is per replica.

Users behind one network address share these figures. For connections with sessions, they share at most 100 connections on Shared 0.5 GB or 250 on Shared 1 GB, on each router replica. On either size, connections without a session share 600 data messages a minute to the application on each router replica. Each signed-in user among them has 600 a minute of their own. The address's connections with sessions share 60,000 a minute, so a hundred signed-in users behind it each send their full 600. An office or a mobile carrier's gateway is one such address.

The platform also closes connections itself:

- A deploy, promote, rollback, or restart that replaces the environment's running copy closes its connections with code 1012 within about 10 seconds of the switch, before the old copy is removed.
- A suspension or an account pause closes the connections with code 1008 in the same time. Under the pause the reason is `account paused`, and new upgrades are refused 429 `account_paused`, as ordinary requests are.
- A router replica that stops admits no further upgrade, sends each of its connections a close with code 1012, and waits at most 10 seconds for the closes before it exits. An upgrade it refuses meanwhile carries `Retry-After: 1`, and its `detail` says the replica is stopping, so the next attempt reaches another replica.

The upgrade counts one backend action, as the request it is. Each data message the client sends counts one more, at its last frame. Ping, pong, and close frames count nothing, and neither do the messages your server sends. The bytes the router sends to the client count as data transfer, added each minute while the connection is open, so they count in the month they cross.

An upgrade refused before it reaches the application counts nothing. An upgrade that reaches the application counts one backend action even when the application returns an ordinary HTTP response instead of switching protocols. The bytes of the answer the router writes count as data transfer. An upgrade the router forwards that fails before any answer, refused 502 `upstream_failed`, also counts one backend action, as a request that fails this way does.

## Expected result

The client's handshake is answered 101, and the connection opens. Messages pass both ways until the client or the server closes the connection, or the router closes it with a code from step 5. `read_logs` with the source `router` shows one `sockets_ended` record each minute for each reason connections ended, with its `reason`, its `code`, and its `count`. It also gives the total and longest duration in milliseconds, `duration_ms_sum` and `duration_ms_max` ([Read logs and counters](/cloud/guides/read-logs-and-counters/)). `read_usage` counts the upgrade and each message the client sent in `backend_actions`.

## Refusals

See the [refusals reference](/cloud/reference/refusals/) for other platform errors.

A refused upgrade is answered on the connection with the status and a JSON body naming the refusal, and the connection then closes. An upgrade also meets the refusals an ordinary request on the hostname meets, such as 429 `rate_capped`, 429 `account_paused` and 401 `authentication_required`.

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `websockets_not_declared` | 400 | The application's manifest declares no `websockets` member. | Add the member and submit the manifest (step 1). |
| `origin_not_admitted` | 403 | The handshake's `Origin` is neither the hostname's own origin nor one the declaration lists. | Open the connection from a page on the application's hostname, or list the page's origin and submit the manifest (step 3). |
| `upgrade_not_served` | 400 | The upgrade's path is under `/__account/`, `/__router/`, or `/.well-known/`, which the platform answers itself. | Use a path of the application's own. |
| `invalid_request` | 400 | The handshake carried a body: a `Content-Length` above zero or a `Transfer-Encoding`. | Send the handshake without a body. |
| `websockets_not_yet_served` | 400 | WebSocket upgrades to shared compute are switched off for this estate. | Read `detail` and report the refusal with `submit_feedback`. No redeploy is needed when the platform enables WebSockets there. |
| `socket_limit_reached` | 429 | A connection limit on the router replica was reached. The `detail` gives the limit. | Close a connection before opening another, or retry with a growing wait. A stopping replica's answer carries `Retry-After: 1`, and the next attempt reaches another replica. |
| `websockets_disabled` | 503 | The platform's switch for WebSocket upgrades is off, so the router refuses every upgrade. Requests are served as before, and nothing on your side caused it. | Open the connection again later. |

## Related

- [The manifest](/cloud/concepts/the-manifest/) lists the `websockets` member beside the others.
- [Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/#websocket-connections) says how an upgrade request counts toward the request limits.
- [Size and usage](/cloud/guides/plan-and-usage/) covers sizes, connection limits and usage.
- [Verifying an end user](/cloud/concepts/verifying-an-end-user/) explains the session header the upgrade request carries.
- [Run your app on your computer](/cloud/guides/run-your-application-on-your-machine/) runs the server for a local test.
