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

# CSRF protection

> secret_csrf, $.csrf(), @{csrf}, DEF.onCSRFcreate and DEF.onCSRFcheck.

The configuration keys, the methods and the delegates of CSRF tokens. The guide [CSRF protection](../../guides/csrf/) explains how to protect a form, an API and a WebSocket.

## API

### secret_csrf : String

Type: `config`

The key of the CSRF tokens.

Returns: `String`

The key that encrypts the token. With an empty value `$.csrf()` returns an empty string and `DEF.onCSRFcheck()` returns `true` for every request. The lifetime of a token is in `$csrfexpiration` (see [Configuration](../../reference/configuration/)).

Default: `''`.

Example: In the config file
```text
secret_csrf     : a-long-random-text
$csrfexpiration : 2 hours
```

### @{csrf}

Type: `command`

Prints a CSRF token in a view.

The same token as `$.csrf()` (see [Controller](../../reference/controller/)). In a view rendered without a controller it prints nothing.

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

### DEF.onCSRFcreate = function($)

Type: `delegate`

Creates the token of $.csrf() and @{csrf}.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | The request. |

Returns: `String` The token.

The default function encrypts the IP address, a hash of the `User-Agent` header and the expiration with `CONF.secret_csrf`. Replace it together with `DEF.onCSRFcheck`.

Example: A token of the session
```js
DEF.onCSRFcreate = function($) {
	return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};
```

### DEF.onCSRFcheck = function($)

Type: `delegate`

Checks the token of a request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | The request. |

Returns: `Boolean` `true` when the request is allowed.

The default function reads the header `x-csrf-token` or the query argument `csrf`, decrypts it and compares the IP address, the browser and the expiration. Without `CONF.secret_csrf` it returns `true`. The framework calls it only for WebSocket routes with the flag `@csrf`: a refused client is disconnected. In HTTP routes call it from a middleware.

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

ROUTE('POST /contact/ #csrf', $ => $.success());
```
