Skip to main content

Import

Usage

Options

The csrf middleware accepts an optional CSRFOptions object:
string | string[] | ((origin: string, context: Context) => boolean | Promise<boolean>)
Allowed origins for requests. Can be:
  • A single origin string (e.g., 'https://example.com')
  • An array of allowed origins
  • A function that returns true to allow or false to deny
  • Default: Only same origin as the request URL
'same-origin' | 'same-site' | 'cross-site' | 'none' | string[] | ((secFetchSite: string, context: Context) => boolean | Promise<boolean>)
Sec-Fetch-Site header validation. Can be:
  • A single allowed value (e.g., 'same-origin')
  • An array of allowed values (e.g., ['same-origin', 'same-site'])
  • A function that returns true to allow or false to deny
  • Default: Only allows 'same-origin'

Signature

Examples

Basic usage

Allow specific origins

Multiple origins

Allow same-site requests

Allow multiple Sec-Fetch-Site values

Dynamic Sec-Fetch-Site validation

Dynamic origin validation

Async validation

Behavior

  • Only validates non-safe HTTP methods (POST, PUT, DELETE, PATCH, etc.)
  • Only validates form submissions (Content-Type: application/x-www-form-urlencoded, multipart/form-data, or text/plain)
  • Request is allowed if EITHER validation passes:
    • Sec-Fetch-Site header matches allowed values, OR
    • Origin header matches allowed origins
  • Returns 403 Forbidden if both validations fail
  • Safe methods (GET, HEAD) are always allowed
  • If neither Origin nor Sec-Fetch-Site header is present, request is denied