---
title: 'CSRF'
description: "Send your framework's CSRF token with every request the engine makes and every native form post."
order: 13
---

# CSRF

`createFormEngine({ csrf })` takes a policy that reads your CSRF token. The engine then sends it with the requests it makes and with a native form post. It is off unless you configure it.

```ts title="csrf.ts"
import { csrf } from '@schema-engine/forms/csrf';
import { createFormEngine } from '@schema-engine/forms';

/** Rails renders the token into `<meta name="csrf-token" content="...">`. */
export const fromMeta = csrf.fromMeta('csrf-token', { header: 'X-CSRF-Token', field: 'authenticity_token' });

/** Django keeps it in the `csrftoken` cookie, which must not be `HttpOnly`. */
export const fromCookie = csrf.fromCookie('csrftoken', { header: 'X-CSRFToken', field: 'csrfmiddlewaretoken' });

/** Anywhere else: a global the server rendered, a store, a call. */
export const fromGlobal = csrf.custom({
	token: () => (globalThis as { csrfToken?: string }).csrfToken,
	header: 'X-CSRF-Token',
});

/** Your engine: add the elements you register beside `csrf`. */
export const engine = createFormEngine({ csrf: fromMeta });
```

`@schema-engine/forms/csrf` exports `csrf`, three readers that each return the policy:

| Reader                                 | Reads                                   |
| -------------------------------------- | --------------------------------------- |
| `csrf.fromMeta(name, placement)`       | The `content` of `<meta name="...">`.   |
| `csrf.fromCookie(name, placement)`     | The decoded value of the cookie `name`. |
| `csrf.custom({ token, ...placement })` | Whatever `token()` returns.             |

`placement` is `{ header, field? }`: the request header that carries the token, and the name of the hidden input a native post carries it in. The token is read when a request is made and never kept, so a rotated token is picked up and an empty one is none. Nothing touches `document` when the module is imported, so it is safe on a server, where the token is `undefined`.

## Where it applies

| Where                     | How                                                                      |
| ------------------------- | ------------------------------------------------------------------------ |
| Requests the engine makes | `engine.fetch`, which the `async` validation rule uses.                  |
| Actions                   | `context.fetch` is the same function.                                    |
| `onSubmit`                | The `fetch` in its second argument is the same function.                 |
| A native post (Radiant)   | A hidden input named by `field`, added right before the post. See below. |

Use that `fetch` for your own requests, and the token is never something a handler remembers. The token is not in the config, the payload or the submitted values.

## The rules

- **Same origin, unsafe method.** `engine.fetch` adds the header only to a same-origin request with `POST`, `PUT`, `PATCH` or `DELETE`. The URL is resolved against the document's base URL (`<base href>` included) and compared with `location`. A cross-origin request, a safe method, a missing token and a page with no `location` (a server) send no header. A header the caller set under the same name is replaced.
- **A native post.** The form gets the hidden input only when the policy has a `field`, there is a token, the method is `post` (any case) and the action is same-origin, resolved like a request (an empty action is the page itself). A `get` or `dialog` form and a cross-origin action get none, so the token never reaches a URL or another origin. A token an earlier post left in the form is removed when the next post must not carry it. React has no native post.
- **`formmethod` and `formaction`.** To decide for your own post, call `csrfFieldFor(engine.getCsrf(), { method, action })` from `@schema-engine/forms/csrf` with the method and action the submission will use. When a submit button sets `formmethod` or `formaction`, those are the effective ones.

## Framework conventions

Each framework names the token its own way. These are their defaults; check your app's configuration.

| Framework | Source of the token                                   | Header                                            | Form field            | Policy                                                                                  |
| --------- | ----------------------------------------------------- | ------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------- |
| Rails     | `<meta name="csrf-token">` from `csrf_meta_tags`      | `X-CSRF-Token`                                    | `authenticity_token`  | `csrf.fromMeta('csrf-token', { header: 'X-CSRF-Token', field: 'authenticity_token' })`  |
| Phoenix   | `<meta name="csrf-token">` from `get_csrf_token()`    | `x-csrf-token`                                    | `_csrf_token`         | `csrf.fromMeta('csrf-token', { header: 'x-csrf-token', field: '_csrf_token' })`         |
| Laravel   | `<meta name="csrf-token">` or the `XSRF-TOKEN` cookie | `X-CSRF-TOKEN`, or `X-XSRF-TOKEN` from the cookie | `_token`              | `csrf.fromMeta('csrf-token', { header: 'X-CSRF-TOKEN', field: '_token' })`              |
| Django    | The `csrftoken` cookie, which must not be `HttpOnly`  | `X-CSRFToken`                                     | `csrfmiddlewaretoken` | `csrf.fromCookie('csrftoken', { header: 'X-CSRFToken', field: 'csrfmiddlewaretoken' })` |
| Your own  | Anything: a global, a store, a call                   | Your choice                                       | Your choice           | `csrf.custom({ token, header, field })`                                                 |

## When you do not need it

A browser sends cookies with a cross-site request unless the cookie says otherwise. If your session cookie is `SameSite=Lax` or `Strict`, it is not sent with a cross-site `POST`, so a forged request arrives without a session. Many apps rely on that alone, and some frameworks still check a token as well. If yours does not require one, leave `csrf` off. If it does, or you serve the same session to other origins, configure it.
