Now, every non-safe request will be validated against CSRF attacks.
Note: If you add this middleware to the root route, it will apply to
every route in your application. If your app has API routes that should
accept cross-site requests (e.g., for webhooks or third-party integrations),
you should move the CSRF middleware to a layout route that wraps only your
UI routes, leaving API routes unprotected by CSRF validation.
The middleware uses the Sec-Fetch-Site header to determine request origin.
Requests from same-origin or same-site are automatically allowed. For
cross-site requests, you can specify trusted origins to allow.
The request origin is determined by checking (in order):
The Origin header
The Referer header
The request.referrer property
The CSRF middleware can be customized by passing an options object to the
createCsrfMiddleware function.
You can allow cross-site requests from specific origins using a string:
The CSRF middleware protects your application from Cross-Site Request Forgery attacks by validating that requests originate from trusted sources.
To use it, you need to add it to the
middlewarearray in yourapp/root.tsxfile.Now, every non-safe request will be validated against CSRF attacks.
The middleware uses the
Sec-Fetch-Siteheader to determine request origin. Requests fromsame-originorsame-siteare automatically allowed. Forcross-siterequests, you can specify trusted origins to allow.The request origin is determined by checking (in order):
OriginheaderRefererheaderrequest.referrerpropertyThe CSRF middleware can be customized by passing an options object to the
createCsrfMiddlewarefunction.You can allow cross-site requests from specific origins using a string:
Or using a RegExp for pattern matching:
Or using an array of strings and RegExps:
Or using a function for dynamic validation:
The function can also be async:
You can customize which HTTP methods skip CSRF validation:
You can allow requests with missing or invalid origin headers:
You can provide a custom handler for untrusted requests:
By default, untrusted requests will receive a 403 Forbidden response.
Author
Sergio XalambrÃ