packages/csrf-middleware/README.md
CSRF protection middleware for Remix. It provides synchronizer-token validation backed by session storage, plus origin checks for unsafe requests.
Origin/Referer for unsafe methods with customizable policiesnpm i remix
This middleware requires session-middleware to run before it.
import { createCookie } from 'remix/cookie'
import { createRouter } from 'remix/fetch-router'
import { createCookieSessionStorage } from 'remix/session/cookie-storage'
import { session } from 'remix/session-middleware'
import { csrf, getCsrfToken } from 'remix/csrf-middleware'
let sessionCookie = createCookie('__session', { secrets: ['secret1'] })
let sessionStorage = createCookieSessionStorage()
let router = createRouter({
middleware: [session(sessionCookie, sessionStorage), csrf()],
})
router.get('/form', (context) => {
let token = getCsrfToken(context)
return new Response(`
<form method="post" action="/submit">
<input type="hidden" name="_csrf" value="${token}" />
<button type="submit">Submit</button>
</form>
`)
})
By default, csrf() checks token values in this order:
x-csrf-token, x-xsrf-token, csrf-token_csrf (requires formData() middleware to parse request bodies)_csrfYou can override extraction using value(context).
Headers and form fields are the preferred transports. Query param fallback exists for compatibility, but it is the weakest option because tokens are more likely to be exposed in logs, history, and copied URLs.
For unsafe methods (POST, PUT, PATCH, DELETE), the middleware validates request origin.
Origin or Referer is presentorigin as string, regex, array, or functionallowMissingOrigin (default true)csrf(). Origin and Referer checks are an additional signal, not the only protection.Origin and Referer are both missing. Set allowMissingOrigin: false if your deployment wants to require provenance headers on unsafe requests.cop-middleware in front of csrf().Modern browsers now provide stronger cross-origin signals like Sec-Fetch-Site, and explicit
SameSite=Lax cookies already block many CSRF attacks. We have considered the lighter,
tokenless model used by Go's CrossOriginProtection, and we think it is a good fit when a
deployment can make all of the guarantees that model depends on.
Remix cannot assume those guarantees for every app. csrf() still exists as the conservative
option for apps that want synchronizer tokens in addition to origin checks, especially for
session-backed HTML form workflows and mixed deployment environments.
If your deployment can guarantee the prerequisites for the tokenless model, this middleware is
optional. In that case, cop-middleware
may be a better fit.
cop-middleware - Middleware for tokenless cross-origin protection using browser provenance headersfetch-router - Router for the web Fetch APIsession-middleware - Session middleware required by csrf()form-data-middleware - Needed for form body token extractionSee LICENSE