CSRF Protection
Cross-site request forgery is an attack where a malicious page tricks a logged-in user's browser into making a state-changing request to your app. Fast protects against it automatically the moment you enable sessions, so most of the time you do not have to think about it beyond adding one token to your forms.
It is on by default
When you call use_session(), Fast registers CSRF middleware for you. It guards every method that changes state, POST, PUT, PATCH, and DELETE, while leaving safe methods like GET, HEAD, and OPTIONS alone.
For a protected request to pass, it must present a valid token in one of three ways:
- an
X-CSRF-Tokenheader; - a form field named
_token, as produced bycsrf_field(); - a
_tokenfield in a JSON body.
If the token is missing or does not match, Fast returns HTTP 419 and the handler never runs.
Protecting a form
The easiest path is csrf_field(), which prints a hidden input carrying the token. Drop it into any form that posts to your app:
<form method="post" action="/profile">
<?= csrf_field() ?>
<input name="name">
<button>Save</button>
</form>
That is the whole story for classic HTML forms. The hidden field carries the token, the middleware checks it, and you are protected.
Protecting AJAX and fetch requests
If your front end sends requests with fetch or an XHR, grab the raw token with csrf_token() and send it as a header:
get('/csrf', fn () => ['token' => csrf_token()]);
fetch('/profile', {
method: 'POST',
headers: { 'X-CSRF-Token': token },
body: JSON.stringify({ name: 'Ada' }),
});
When to disable it
CSRF protection assumes a browser that automatically sends cookies, which is exactly the situation that makes forgery possible. If you are building a pure API that authenticates with, say, a bearer token in the Authorization header rather than a session cookie, CSRF does not apply and you can turn it off:
use_session($config, csrf: false);
Only disable CSRF for a deliberately non-cookie API with its own, independently designed authentication boundary. If your app uses session cookies for anything, leave CSRF on. It is cheap and it closes a real, common vulnerability.
How the token stays trustworthy
The CSRF token is a synchronizer token tied to the session. Because the session itself is encrypted and authenticated, the token cannot be forged or replayed from a tampered cookie. When a session is regenerated, for instance at login, the protection travels with it seamlessly.
With sessions and CSRF in place, the natural next step is knowing who the user is. That is Authentication.