The CSRF Token middleware protects your application from Cross-Site Request
Forgery attacks by using a token-based approach where a random token is
stored in a cookie and must be included in form submissions.
Note: This depends on @oslojs/crypto, @oslojs/encoding, and
React Router.
The middleware will automatically validate the token on non-safe requests
(POST, PUT, DELETE, PATCH) and reject requests with invalid or missing
tokens with a 403 Forbidden response.
You can customize the middleware behavior:
let [csrfTokenMiddleware, getCsrfToken] = createCsrfTokenMiddleware({ cookie, // The name of the form field containing the token (default: "csrf") formDataKey:"csrf", // A secret to sign the token for extra security secret:process.env.CSRF_SECRET, // Custom handler for invalid tokens onInvalidToken(error, request, context) { returnnewResponse("Invalid CSRF token", { status:403 }); }, });
You can allow cross-site requests from specific trusted origins to bypass
token validation:
let [csrfTokenMiddleware, getCsrfToken] = createCsrfTokenMiddleware({ cookie, origin:"https://trusted.com", });
Or using a RegExp for pattern matching:
let [csrfTokenMiddleware, getCsrfToken] = createCsrfTokenMiddleware({ cookie, origin: /\.trusted\.com$/, });
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 CSRF Token middleware protects your application from Cross-Site Request Forgery attacks by using a token-based approach where a random token is stored in a cookie and must be included in form submissions.
To use it, you need to add it to the
middlewarearray in yourapp/root.tsxfile.Use the
getCsrfTokenfunction in your root loader to retrieve the token and pass it to your forms:You can use this with the
AuthenticityTokenProviderandAuthenticityTokenInputcomponents fromremix-utils/csrf/react:Then in your forms:
The middleware will automatically validate the token on non-safe requests (POST, PUT, DELETE, PATCH) and reject requests with invalid or missing tokens with a 403 Forbidden response.
You can customize the middleware behavior:
You can allow cross-site requests from specific trusted origins to bypass token validation:
Or using a RegExp for pattern matching:
Or using an array of strings and RegExps:
Or using a function for dynamic validation:
Author
Sergio XalambrÃ