Import
Usage
Options
Thecsrf middleware accepts an optional CSRFOptions object:
Allowed origins for requests. Can be:
- A single origin string (e.g.,
'https://example.com') - An array of allowed origins
- A function that returns
trueto allow orfalseto deny - Default: Only same origin as the request URL
secFetchSite
'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
trueto allow orfalseto 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, ortext/plain) - Request is allowed if EITHER validation passes:
Sec-Fetch-Siteheader matches allowed values, OROriginheader matches allowed origins
- Returns 403 Forbidden if both validations fail
- Safe methods (GET, HEAD) are always allowed
- If neither
OriginnorSec-Fetch-Siteheader is present, request is denied