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

# WebSockets

> Declare WebSocket routes, handle clients and messages in the WebSocket controller, and connect to WebSocket servers with WEBSOCKETCLIENT().

A WebSocket route keeps a connection open between the browser and the server. In Total.js you declare it with `ROUTE()` and the `SOCKET` method. The action of the route does not answer a request: it runs **once**, when the first client connects, and its `this` is a **WebSocket controller** shared by every client of that route.

```js
exports.install = function() {
	ROUTE('SOCKET /chat/', chat);
};

function chat() {

	var self = this;

	self.on('open', function(client) {
		client.send({ type: 'welcome', id: client.id });
	});

	self.on('message', function(client, message) {
		// Send the message to everybody
		self.send({ type: 'message', from: client.id, body: message.body });
	});

	self.on('close', function(client) {
		self.send({ type: 'leave', id: client.id });
	});
}
```

The full list of properties and methods is in the reference of [WebSockets](../../reference/websockets/).

## Declaring a route

`ROUTE('SOCKET /path/', action, [flags], [length])` registers the route. `WS` and `WSS` are accepted as aliases of `SOCKET`. A `+` before the method allows only signed-in users and a `-` only anonymous users, as in other routes:

```js
exports.install = function() {
	ROUTE('+SOCKET /notifications/', notifications);
	ROUTE('SOCKET /live/{room}/', live, ['json'], 64);
};

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

Dynamic parts of the URL arrive as arguments of the action and in `this.params`. The `length` argument (or a number in the flags) is the maximum size of one message in **kB**. The default comes from `CONF.default_websocket_maxlength` (`2` kB). A bigger frame closes the connection with code `1009`.

## Flags

| Flag | Meaning |
| --- | --- |
| `json` | Messages are JSON (the default). Incoming messages are parsed, outgoing objects are serialized. |
| `text` or `plain` | Messages are strings. |
| `binary` | Messages are binary; `message` receives a `Buffer`. |
| `raw` | Turns off `json` and `binary`; messages are handled as text. |
| `buffer` | The `message` event always receives the raw `Buffer`. |
| `authorize`, `logged` | Only signed-in users (the same as `+`). |
| `unauthorize`, `unlogged` | Only anonymous users (the same as `-`). |
| `@role` | Marks a role; the route also becomes `authorize`. |
| `http://…`, `https://…` | Allowed origins. The `Origin` header must contain one of them. |
| `#name` or `&name` | Middleware run before the connection is accepted. |
| `id:name` | An identifier of the route. |
| `debug`, `release`, `http`, `https` | Limit the route to a mode or a protocol. |
| any other word | A required sub-protocol: the client must send it in `Sec-WebSocket-Protocol`. |
| a number | The maximum message size in kB. |
| an object | Options passed to the middleware. |

```js
ROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);
```

This route accepts only clients from `https://www.example.com` that ask for the `chat` sub-protocol, and messages up to 128 kB.

## How connections are grouped

Every route has one controller per URL. The first client creates it and runs the action; later clients on the same URL join the existing controller, and the action is not called again. That is why the action registers events instead of answering.

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

Without more code the controller stays in memory after the last client leaves. Call `this.autodestroy()` to destroy it 5 seconds after the last client disconnects; the next client creates a new one and the action runs again:

```js
function room() {
	var self = this;
	self.autodestroy(function() {
		console.log('Room closed:', self.url);
	});
}
```

## Receiving and sending

With the default `json` flag, `message` receives a parsed object; invalid JSON is ignored. `client.send(obj)` sends to one client and `this.send(obj)` sends to all clients of the controller. The second argument of `this.send()` filters the receivers:

```js
function chat() {
	var self = this;
	self.on('message', function(client, message) {

		// Everybody except the sender
		self.send(message, function(c) {
			return c !== client;
		});

		// Only users of one company
		self.send(message, function(c, msg, params) {
			return c.user && c.user.companyid === params.companyid;
		}, { companyid: client.user.companyid });
	});
}
```

`this.find(fn)` returns the first client for which `fn` returns `true`, and `this.clients()` returns all clients as an array. `this.online` is the number of connected clients and `this.connections` maps client ids to clients.

## The client of a connection

Every connected client has `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` and `protocol`. `user` is the value accepted by your `AUTH()` delegate:

```js
// definitions/auth.js
AUTH(function($) {
	// $.websocket is true for WebSocket connections
	var token = $.query.token || $.cookie('token');
	if (token === 'secret')
		$.success({ id: 1, name: 'Peter' });
	else
		$.invalid();
});

// controllers/default.js
exports.install = function() {
	ROUTE('+SOCKET /private/', privatechannel);
};

function privatechannel() {
	this.on('open', function(client) {
		client.send({ hello: client.user.name });
	});
}
```

A client that fails authorization is closed with code `4001`, a URL without a route with `4004`, and invalid URL parameters with `4000`.

`client.close([message], [code])` closes one client and `this.close([message], [code])` closes all of them. The default code is `1000`.

## Ping and stale connections

The framework pings every connected client every `CONF.default_interval_websocket_ping` milliseconds (default `20000`). The answer sets `client.latency`. A client that did not answer, or whose latency is higher than `CONF.default_websocket_maxlatency` (default `2000` ms), is closed at the next round. Set `default_websocket_maxlatency` to `0` to turn the pinger off.

## WebSocket API

A route can process `API` routes over the socket. Declare the API with `@name` and use the same name in the socket route:

```js
exports.install = function() {
	ROUTE('API @chat -messages_list   *Messages --> list');
	ROUTE('API @chat +messages_create *Messages --> create');
	ROUTE('SOCKET /chat/ @chat');
};
```

A `SOCKET` route with `@name` and no action calls `this.api('@name')` and `this.autodestroy()` for you. The client sends `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` and gets the same object back with `success: true` and `data`, or `error: true` and the errors.

## Connecting from the server

`WEBSOCKETCLIENT()` creates a WebSocket client, for example to connect one Total.js app to another:

```js
WEBSOCKETCLIENT(function(client) {

	client.options.reconnect = 5000;
	client.headers['x-token'] = 'secret';

	client.on('open', function() {
		client.send({ type: 'hello' });
	});

	client.on('message', function(message) {
		console.log(message);
	});

	client.on('close', function(code, message) {
		console.log('Closed', code, message);
	});

	client.connect('ws://127.0.0.1:8000/chat/');
});
```

`client.options.type` is `json` by default; use `text`, `binary` or `buffer` for other data. The client reconnects 3 seconds after the connection is lost (`options.reconnect`); `client.close()` stops reconnecting and `client.destroy()` frees the client. `client.api(schema, data, callback)` calls the WebSocket API of the server:

```js
client.api('messages_list', { page: 1 }, function(err, response) {
	console.log(err, response);
});
```

## Configuration

| Key | Default | Meaning |
| --- | --- | --- |
| `allow_websocket` | `true` | Enables WebSocket routes. |
| `allow_websocket_compression` | `true` | Allows `permessage-deflate` compression. |
| `default_websocket_maxlength` | `2` | Maximum message size in kB. |
| `default_websocket_maxlatency` | `2000` | Maximum ping latency in ms; `0` disables the pinger. |
| `default_interval_websocket_ping` | `20000` | Interval of the ping in ms. |
| `default_websocket_encodedecode` | `false` | Encodes messages with `encodeURIComponent()` and decodes them. |
