---
title: CSRF protection
project: Total.js V5
version: 0.0.20
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/csrf/
updated: 2026-12-02T17:11:05.487Z
---

# CSRF protection

> Create a CSRF token for a page, check it in a middleware of your routes and in WebSocket routes.

A browser sends the cookies of your application also with a request that another website started. A CSRF token stops such requests: your page gets a token from the server and sends it back with each change, and the other website cannot read it.

The default cookies of the framework have `SameSite=Lax`, so browsers do not send them with a `POST` request from another website. The token is a second protection, useful with `$cookiesamesite : None` or for forms that work without a login.

The functions are in the [reference](../../reference/csrf/).

## Turning it on

Set a secret in the `config` file. Without it the token is an empty string and every check passes:

```
secret_csrf     : a-long-random-text
$csrfexpiration : 2 hours
```

A token is bound to the IP address and the browser (`User-Agent`) of the visitor and is valid for the time in `$csrfexpiration` (30 minutes by default).

## The token in the page

`@{csrf}` prints the token in a view, and `$.csrf()` creates it in a controller:

```html
<form action="/contact/?csrf=@{csrf}" method="POST">
	<input type="text" name="name" />
	<button>Send</button>
</form>
```

```js
ROUTE('GET /csrf/', function($) {
	$.json({ token: $.csrf() });
});
```

The server reads the token from the header `x-csrf-token` or from the query argument `csrf`. JavaScript sends the header:

```js
fetch('/contact/', { method: 'POST', headers: { 'content-type': 'application/json', 'x-csrf-token': token }, body: JSON.stringify(data) });
```

## Checking the token

HTTP routes do not check the token by themselves. Write a [middleware](../../guides/middleware/) with `DEF.onCSRFcheck($)` and put it on the routes that change something:

```js
// middleware/csrf.js
MIDDLEWARE('csrf', function($, next) {
	if (DEF.onCSRFcheck($))
		next();
	else
		$.invalid(403);
});
```

```js
ROUTE('GET  /contact/', 'contact');
ROUTE('POST /contact/ #csrf', function($) {
	$.success();
});
```

A `POST` without a valid token gets the status `403`.

A WebSocket route checks the token with the flag `@csrf` (see [WebSockets](../../guides/websockets/)). Browsers cannot set headers on a WebSocket, so the token goes in the address:

```js
ROUTE('SOCKET /live/ @csrf', function($) {
	$.on('message', (client, msg) => client.send(msg));
});
```

```js
new WebSocket('wss://shop.example.com/live/?csrf=' + token);
```

## Your own tokens

`DEF.onCSRFcreate` and `DEF.onCSRFcheck` create and check the token, and you can replace both. This pair binds the token to the session instead of the IP address, which changes on mobile networks. It is for routes of signed-in users, with the sessions of [Authorization](../../guides/authorization/):

```js
// definitions/csrf.js
DEF.onCSRFcreate = function($) {
	return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};

DEF.onCSRFcheck = function($) {
	var token = DECRYPT($.headers['x-csrf-token'] || $.query.csrf || '', CONF.secret_csrf);
	return token && $.sessionid ? token.id === $.sessionid && token.expire > Date.now() : false;
};
```
