---
title: WebSockets
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/websockets/
updated: 2026-11-16T15:41:00.817Z
---

# WebSockets

> The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT().

A `SOCKET` route creates a WebSocket controller shared by all clients of a URL; each connection is a client object, and `WEBSOCKETCLIENT()` connects from the server to other WebSocket servers. The guide [WebSockets](../../guides/websockets/) explains how to use them with examples; this page is the exact reference.

## API

### ROUTE('SOCKET /url/', action, [flags], [length])

Type: `method`

Declares a WebSocket route.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | `SOCKET /path/`, optionally with `+`/`-`, `{params}` and `@apiname` |
| `action` | `Function` | yes |  | Initializes the WebSocket controller |
| `flags` | `Array` | yes |  | Flags, origins, protocols, middleware, a length or an options object |
| `length` | `Number` | yes |  | Maximum message size in kB |

Returns: `FrameworkRoute` The route instance

The URL starts with `SOCKET` (or `WS`, `WSS`). A `+` or `-` before it limits the route to signed-in or anonymous users. `action` runs once, when the first client connects to the URL, with the WebSocket controller as `this` and the dynamic URL parameters as arguments. `length` is the maximum size of one message in kB (default `CONF.default_websocket_maxlength`, `2`). With `@name` in the URL and no action, the route processes the WebSocket API `@name` and destroys itself when the last client leaves.

The flags are described in the entry **WebSocket route flags**.

Example: Chat route
```js
exports.install = function() {
	ROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);
};

function chat(room) {
	var self = this;
	self.autodestroy();
	self.on('message', function(client, message) {
		self.send({ room: room, body: message.body });
	});
}
```

Example: WebSocket API without an action
```js
exports.install = function() {
	ROUTE('API @chat -messages_list *Messages --> list');
	ROUTE('SOCKET /chat/ @chat');
};
```

### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])

Type: `config`

Flags that set the data type, access, origins and protocols of a WebSocket route.

- `json` (default): incoming messages are parsed as JSON (invalid JSON is ignored) and outgoing objects are serialized.
- `text`, `plain`: messages are strings; objects you send are serialized as JSON.
- `binary`: messages are `Buffer` objects.
- `raw`: turns off `json` and `binary` (text mode).
- `buffer`: the `message` event always receives the raw `Buffer`.
- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: signed-in or anonymous users only.
- `@role`: a role flag; it makes the route `authorize`.
- `http://...`, `https://...`: allowed origins; the request `Origin` must contain one of them.
- `#middleware`, `&middleware`: middleware names.
- `id:name`: the route identifier.
- `get`, `csrf`, `http`, `https`, `debug`, `release`: standard route flags.
- Any other word is a required sub-protocol. Every listed protocol must be in the client's `Sec-WebSocket-Protocol` header, otherwise the connection is closed with `4001`.
- A number is the maximum message size in kB; an object is the middleware options.

Example: Binary route for one origin
```js
ROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);

function upload() {
	this.on('message', function(client, buffer) {
		// buffer is a Buffer
	});
}
```

Example: Required sub-protocol
```js
// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');
ROUTE('SOCKET /rpc/', rpc, ['rpc']);
```

### websocket.online

Type: `property`

The number of connected clients.

Returns: `Number`

Updated whenever a client connects or disconnects.

Example: Broadcast the count
```js
function counter() {
	var self = this;
	self.on('open', function() {
		self.send({ online: self.online });
	});
}
```

### websocket.connections

Type: `property`

All connected clients by their id.

Returns: `Object`

An object whose keys are client ids and values are client objects. `websocket.keys` holds the same ids as an array. `websocket.id` is the key of the controller in `F.connections`: the URL followed by `#` and the route flags.

Example: Read a client
```js
var client = this.connections['15'];
```

### websocket.url

Type: `property`

The URL of the connection.

Returns: `String`

The path the first client connected to, with a trailing slash.

### websocket.params

Type: `property`

The dynamic parameters of the URL.

Returns: `Object`

Each `{name}` of the route becomes a key. The same values arrive as arguments of the action.

Example: Room name
```js
ROUTE('SOCKET /rooms/{name}/', room);

function room(name) {
	// name === this.params.name
}
```

### websocket.repository

Type: `property`

An object for your own data.

Returns: `Object`

Created on first access and kept for the life of the controller.

Example: Keep history
```js
function chat() {
	var self = this;
	self.repository.history = [];
	self.on('message', function(client, message) {
		self.repository.history.push(message);
	});
}
```

### websocket.on(name, callback)

Type: `method`

Registers an event handler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Event name |
| `callback` | `Function` | yes |  | Handler |

Returns: `WebSocket` The controller

Events: `open`, `close`, `message`, `error` and `destroy`. `this` in the handler is the controller. `once(name, fn)` registers a handler for one call, `removeListener(name, fn)` and `removeAllListeners([name])` remove handlers, and `emit(name, [args...])` calls the handlers of your own events.

Example: Events
```js
function chat() {
	this.on('open', function(client) {});
	this.on('message', function(client, message) {});
	this.on('close', function(client, code, message) {});
}
```

### websocket.send(message, [comparer], [replacer], [params])

Type: `method`

Sends a message to all clients or to the clients you select.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | The message |
| `comparer` | `Function` | yes |  | `function(client, message, params)` returns `true` to send |
| `replacer` | `Function/Boolean` | yes |  | JSON replacer |
| `params` | `Object` | yes |  | Value passed to `comparer` |

Returns: `WebSocket`

In a `json` route the message is serialized once and sent to every client. `comparer(client, message, params)` returns `true` for the clients that receive the message. `replacer` is passed to `JSON.stringify()`; `true` uses the framework's JSON replacer. When the third argument is not a function, it is used as `params`.

Example: Everybody except the sender
```js
self.on('message', function(client, message) {
	self.send(message, function(c) {
		return c !== client;
	});
});
```

Example: With params
```js
self.send({ type: 'refresh' }, function(client, message, params) {
	return client.user && client.user.role === params.role;
}, { role: 'admin' });
```

### websocket.find(fn)

Type: `method`

Finds the first client that matches a function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(client)` returns `true` for the wanted client |

Returns: `Object` The client or `undefined`

Returns `undefined` when no client matches.

Example: Find a user
```js
var client = this.find(function(client) {
	return client.user && client.user.id === userid;
});
client && client.send({ type: 'notify' });
```

### websocket.clients()

Type: `method`

Returns all connected clients as an array.

Returns: `Array`

Example: List users
```js
var users = this.clients().map(function(client) {
	return client.user ? client.user.name : 'anonymous';
});
```

### websocket.close([message], [code])

Type: `method`

Closes all connected clients.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | Close reason |
| `code` | `Number` | yes |  | Close code, default `1000` |

Returns: `WebSocket`

Every client receives a close frame with `code` (default `1000`) and `message`. The controller itself stays; use `destroy()` to remove it.

Example: Close everybody
```js
this.close('Server restart', 4000);
```

### websocket.destroy()

Type: `method`

Closes all clients and removes the controller.

Returns: `WebSocket`

Emits `destroy`, removes the controller from `F.connections` and frees it. The next client of the URL creates a new controller.

### websocket.autodestroy([callback])

Type: `method`

Destroys the controller when no client is online.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Called before the controller is destroyed |

Returns: `WebSocket`

When the last client disconnects and nobody connects within 5 seconds, `callback` is called (with the controller as `this`) and the controller is destroyed. Calling it again adds another callback.

Example: Auto destroy
```js
function room() {
	this.autodestroy(function() {
		console.log('Destroyed', this.url);
	});
}
```

### websocket.ping()

Type: `method`

Sends a ping to all clients.

Returns: `WebSocket`

The framework calls it on its own every `CONF.default_interval_websocket_ping` ms. The pong answer sets `client.latency`.

### websocket.api(name)

Type: `method` · Since: `0.0.44`

Processes WebSocket API messages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | API name, with or without `@` |

Returns: `WebSocket`

Registers a `message` handler that runs `API` routes with the given `@name` for messages whose `TYPE` is `api`. The message `data` is `{ schema: 'operation/param', data: {} }`; the answer is sent back to the client when the message has `callbackid`, with `success: true` and `data`, or `error: true` and the error items.

Example: Process an API
```js
exports.install = function() {
	ROUTE('API @chat -messages_list *Messages --> list');
	ROUTE('SOCKET /chat/', chat);
};

function chat() {
	this.api('@chat');
	this.autodestroy();
}
```

### websocket.encrypt([enable])

Type: `method`

Encrypts messages with `CONF.secret_encryption`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | yes |  | Default `true` |

Returns: `WebSocket`

When enabled and `CONF.secret_encryption` is set, outgoing text messages are encrypted and incoming ones decrypted. Without an argument it enables encryption.

### websocket.on('open', function(client) {})

Type: `event`

A client connected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | The new client |

Emitted after the client joined the controller, so `this.online` already counts it.

Example: Welcome
```js
this.on('open', function(client) {
	client.send({ type: 'welcome' });
});
```

### websocket.on('message', function(client, message) {})

Type: `event`

A client sent a message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | The sender |
| `message` | `Object/String/Buffer` | yes |  | The message |

`message` is an object in `json` routes, a string in `text` routes and a `Buffer` in `binary` or `buffer` routes.

Example: Echo
```js
this.on('message', function(client, message) {
	client.send(message);
});
```

### websocket.on('close', function(client, code, message) {})

Type: `event`

A client disconnected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | The client |
| `code` | `Number` | yes |  | Close code |
| `message` | `String` | yes |  | Close reason |

`code` and `message` come from the close frame of the client, when it sent one.

### websocket.on('error', function(err, client) {})

Type: `event`

A socket error occurred.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | yes |  | The error |
| `client` | `Object` | yes |  | The client |

### websocket.on('destroy', function() {})

Type: `event`

The controller is being destroyed.

### client.id

Type: `property`

The unique id of the connection.

Returns: `String`

A numeric string. It is also available as `client.ID` and is the key in `websocket.connections`. `client.online` is `true` while the connection is open, and `client.controller` (or `client.container`) is the WebSocket controller.

### client.user

Type: `property`

The user accepted by `AUTH()`.

Returns: `Object`

You can also assign a value. `client.session` and `client.sessionid` hold the session values from the request.

Example: Private message
```js
var client = self.find(function(c) {
	return c.user && c.user.id === message.to;
});
```

### client.query

Type: `property`

The query string of the connection URL.

Returns: `Object`

The values are strings. `client.get` is an alias.

Example: Token in the URL
```js
// new WebSocket('wss://example.com/live/?channel=sport')
this.on('open', function(client) {
	client.channel = client.query.channel;
});
```

### client.headers

Type: `property`

The headers of the upgrade request.

Returns: `Object`

Also available: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` and `client.req`. `client.protocol` is the array of sub-protocols from `Sec-WebSocket-Protocol`.

### client.latency

Type: `property`

The latency of the last ping in ms.

Returns: `Number`

Set when the client answers a ping. Clients without an answer or with a higher latency than `CONF.default_websocket_maxlatency` are closed.

### client.send(message, [raw], [replacer])

Type: `method`

Sends a message to this client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | The message |
| `raw` | `Boolean` | yes |  | Do not serialize (json routes) |
| `replacer` | `Function/Boolean` | yes |  | JSON replacer; `true` uses the framework's replacer |

Returns: `Object` The client

In a `json` route objects are serialized; with `raw` set to `true` the message is sent as it is (a JSON string you already have). In a `text` route objects are serialized and other values converted to strings. In a `binary` route the message must be a `Buffer`. Nothing happens if the client is closed.

Example: Reply
```js
this.on('message', function(client, message) {
	client.send({ ok: true, id: message.id });
});
```

### client.close([message], [code])

Type: `method`

Closes this connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | Close reason |
| `code` | `Number` | yes |  | Close code, default `1000` |

Returns: `Object` The client

Sends a close frame with `code` (default `1000`) and `message`. The arguments can also be passed in the order `(code, message)`.

Example: Kick a client
```js
client.close('Kicked', 4100);
```

### client.cookie(name)

Type: `method`

Reads a cookie of the upgrade request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cookie name |

Returns: `String`

Example: Read a cookie
```js
var token = client.cookie('token');
```

### client.hostname([path])

Type: `method`

Returns the hostname with an optional path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Path to append |

Returns: `String`

`client.host()` is an alias.

### F.findConnection(path)

Type: `method`

Finds a WebSocket controller by its id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String/RegExp` | yes |  | Part of the id or a regular expression |

Returns: `WebSocket` The controller or `undefined`

Returns the first controller whose id contains `path` (or matches a `RegExp`). Controllers are kept in `F.connections`.

Example: Send from an HTTP route
```js
function notify() {
	var ws = F.findConnection('/notifications/');
	ws && ws.send({ type: 'refresh' });
	this.success();
}
```

### F.findConnections([path])

Type: `method`

Finds WebSocket controllers.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String/RegExp` | yes |  | Part of the id or a regular expression |

Returns: `Array`

Without `path` it returns all controllers.

Example: All rooms
```js
F.findConnections('/rooms/').forEach(function(ws) {
	ws.send({ type: 'shutdown' });
});
```

### ON('websocket_begin', function(controller, client) {})

Type: `event`

A client joined a WebSocket controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | The controller |
| `client` | `Object` | yes |  | The client |

### ON('websocket_end', function(controller, client) {})

Type: `event`

A client left a WebSocket controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | The controller |
| `client` | `Object` | yes |  | The client |

### CONF.default_websocket_maxlength

Type: `config`

The default maximum message size in kB.

Returns: `Number`

Default `2`. A route overrides it with its `length`.

### CONF.default_websocket_maxlatency

Type: `config` · Since: `0.0.59`

The maximum ping latency in ms.

Returns: `Number`

Default `2000`. Clients with a higher latency, or without a pong, are closed. `0` turns the pinger off. The ping runs every `CONF.default_interval_websocket_ping` ms (default `20000`; values below `1000` use `20000`).

### CONF.allow_websocket

Type: `config`

Enables WebSocket routes.

Returns: `Boolean`

Default `true`. `CONF.allow_websocket_compression` (default `true`) allows `permessage-deflate`, and `CONF.default_websocket_encodedecode` (default `false`) turns on URI encoding of messages.

### WEBSOCKETCLIENT([callback])

Type: `method`

Creates a WebSocket client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(client)` |

Returns: `WebSocketClient`

`callback(client)` is called at once with the new client (also as `this`). Set options, headers and events there, then call `client.connect()`.

Example: Connect
```js
WEBSOCKETCLIENT(function(client) {
	client.on('open', function() {
		client.send({ type: 'hello' });
	});
	client.on('message', function(message) {
		console.log(message);
	});
	client.connect('wss://example.com/chat/');
});
```

### websocketclient.options

Type: `property`

Options of the client.

Returns: `Object`

- `type` (`'json'`): `json`, `text`, `binary` or `buffer`.
- `compress` (`true`): asks for `permessage-deflate`.
- `reconnect` (`3000`): ms before reconnecting after a closed connection; `0` disables it.
- `reconnectserver` (`false`): also reconnect after a connection error or an unexpected HTTP response.
- `masking` (`false`): masks outgoing frames.
- `encodedecode` (`false`): URI encoding of messages.
- `encrypt`: a secret to encrypt and decrypt text messages.
- `length`: maximum size of a decompressed message in bytes.
- `rejectunauthorized` (`false`): rejects invalid TLS certificates.
- `key`, `cert`, `dhparam`: TLS options.

Example: Text client
```js
WEBSOCKETCLIENT(function(client) {
	client.options.type = 'text';
	client.options.reconnect = 10000;
	client.connect('ws://127.0.0.1:8000/log/');
});
```

### websocketclient.headers

Type: `property`

Extra headers of the upgrade request.

Returns: `Object`

`websocketclient.cookies` is an object of cookies sent in the `Cookie` header.

Example: Token
```js
client.headers['x-token'] = 'secret';
client.cookies.session = 'abc';
```

### websocketclient.closed

Type: `property`

`true` when the client is not connected.

Returns: `Boolean`

`websocketclient.reconnect` counts the reconnections.

### websocketclient.latency

Type: `property` · Since: `0.0.44`

The latency of the last ping in ms.

Returns: `Number`

Set when the server answers `ping()`.

### websocketclient.connect(url, [protocol], [origin])

Type: `method`

Opens the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String/Object` | yes |  | Server URL |
| `protocol` | `String` | yes |  | Sub-protocol |
| `origin` | `String` | yes |  | Origin |

`url` starts with `ws://` or `wss://`. It can also be an object `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` is sent in `Sec-WebSocket-Protocol` and `origin` in `Sec-WebSocket-Origin`. The connection starts on the next tick.

Example: With a protocol
```js
client.connect('wss://example.com/rpc/', 'rpc');
```

### websocketclient.send(message, [raw], [replacer])

Type: `method`

Sends a message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | The message |
| `raw` | `Boolean` | yes |  | Do not serialize (json) |
| `replacer` | `Function/Boolean` | yes |  | JSON replacer |

Returns: `Boolean` `true` when sent

With `type: 'json'` objects are serialized (unless `raw` is `true`). With `text` objects are serialized and other values converted to strings. With `binary` or `buffer` a non-`Buffer` message is converted to a `Buffer`. Returns `false` when the client is closed.

Example: Send
```js
if (!client.send({ type: 'ping' }))
	console.log('Not connected');
```

### websocketclient.close([message], [code])

Type: `method`

Closes the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String/Boolean` | yes |  | Close reason, or `true` to reconnect |
| `code` | `Number` | yes |  | Close code, default `1000` |

Returns: `WebSocketClient`

Sends a close frame with `code` (default `1000`). It also stops reconnecting, unless `message` is `true`: then the connection closes and the client reconnects. The arguments can be passed as `(code, message)`.

Example: Reconnect
```js
// Close and connect again after options.reconnect ms
client.close(true);
```

### websocketclient.destroy()

Type: `method` · Since: `0.0.42`

Frees the client and stops reconnecting.

Emits `destroy` and removes all event handlers.

### websocketclient.ping([timeout])

Type: `method` · Since: `0.0.44`

Sends a ping to the server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timeout` | `Number` | yes |  | Default `3000` ms |

Returns: `WebSocketClient`

If no pong arrives within `timeout` ms (default `3000`), the client emits `error` with `'Timeout'` and closes. The pong sets `latency`.

Example: Measure latency
```js
setInterval(function() {
	client.ping(5000);
}, 30000);
```

### websocketclient.api([schema], [data], [callback], [timeout])

Type: `method` · Since: `0.0.44`

Calls the WebSocket API of a Total.js server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Operation, e.g. `'messages_read/123'` |
| `data` | `Object` | yes |  | Payload |
| `callback` | `Function` | yes |  | `function(err, response)` |
| `timeout` | `Number` | yes |  | Default `5000` ms |

Returns: `WebSocketClient`

Sends `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` gets the answer; `err` is `408` after `timeout` ms (default `5000`). Without `schema` it only registers the handler for answers.

Example: Call an operation
```js
client.api('messages_list', { page: 1 }, function(err, response) {
	if (err)
		console.log(err);
	else
		console.log(response);
});
```

### websocketclient.on(name, callback)

Type: `method`

Registers an event handler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Event name |
| `callback` | `Function` | yes |  | Handler |

Returns: `WebSocketClient`

Events: `open()`, `message(data)`, `close(code, message)`, `error(err)` and `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` and `emit()` work as in the controller.

Example: Events
```js
client.on('open', function() {});
client.on('message', function(data) {});
client.on('close', function(code, message) {});
client.on('error', function(err) {});
```

### client.session

Type: `property`

The session of the connection.

Returns: `Object`

The session set by your `AUTH()` delegate for the upgrade request. `client.sessionid` is its id. It can be set.

Example: Example
```js
function socket() {
	this.on('open', function(client) {
		console.log(client.sessionid, client.session);
	});
}
```

### client.ping()

Type: `method`

Sends a ping frame to this client.

Returns: `Object` The client.

The answer of the client updates `client.latency`. `websocket.ping()` pings all clients.

Example: Ping one client
```js
function socket() {
	this.on('open', function(client) {
		client.ping();
	});
}
```

### websocketclient.url

Type: `property`

The URL of the last `connect()`.

Returns: `String`

`websocketclient.protocol` and `websocketclient.origin` keep the other arguments of `connect()`.

Example: Example
```js
WEBSOCKETCLIENT(function(client) {
	client.connect('wss://example.com/live/');
	client.on('open', function() {
		console.log('Connected to', client.url);
	});
});
```
