# Configure a WebSocket route with flags, auth and parameters

> Choose the message type with @text or @binary, require a signed-in user with the + prefix, check a CSRF token with @csrf and read URL parameters in SOCKET routes.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 153249a5572bf8c2fd9e77659ca65a7b282a94a9600af87f3e59004c290776ab
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

A `SOCKET` route takes the same building blocks as an HTTP route. By default messages are JSON objects. `@text` makes the incoming messages plain strings and `@binary` makes them `Buffer`s. In a text route `send(message)` still encodes what it sends as JSON, so a string arrives with quotes; pass `true` as the second argument, `send(message, true)`, to send the string as it is. A `+` before `SOCKET` accepts only users that `AUTH()` approves (the connection is refused otherwise), and `{name}` segments are available in `self.params`. `@csrf` checks a CSRF token before the connection is accepted: send it as the `csrf` query string parameter (`/secure/?csrf=...`), and see the CSRF recipe for `secret_csrf` and `$.csrf()`. A middleware is attached with `#name` as on any route.

```text config
secret_csrf : change-this-secret-in-production
```

```js definitions/auth.js
AUTH(function($) {
	if ($.query.token === 'letmein')
		$.success({ id: '1', name: 'Louis' });
	else
		$.invalid();
});
```

```js controllers/sockets.js
exports.install = function() {
	ROUTE('SOCKET /text/ @text', text);
	ROUTE('SOCKET /bin/ @binary', binary);
	ROUTE('+SOCKET /private/', private_socket);
	ROUTE('SOCKET /room/{name}/', room);
	ROUTE('SOCKET /secure/ @csrf', secure);
	ROUTE('GET /where/', where);
	ROUTE('GET /csrf/', csrf);
};

function text() {
	this.on('message', function(client, message) {
		client.send(typeof(message) + ':' + message.toUpperCase(), true);
	});
}

function binary() {
	this.on('message', function(client, message) {
		client.send(Buffer.from(Buffer.isBuffer(message) ? 'buffer:' + message.length : 'other'));
	});
}

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

function room() {
	var self = this;
	self.on('open', function(client) {
		client.send({ room: self.params.name });
	});
}

function secure() {
	this.on('open', function(client) {
		client.send({ welcome: true });
	});
}

function where($) {
	$.json({ url: $.hostname('/bin/') });
}

function csrf($) {
	$.json({ csrf: $.csrf() });
}
```
