Install using bunx shadcn@latest add @remix-utils/middleware-csrf-token.
Note
This depends on @oslojs/crypto, @oslojs/encoding, and React Router.
The CSRF Token middleware protects your application from Cross-Site Request Forgery attacks using a token-based approach where a random token is stored in a cookie and must be included in form submissions.
The middleware automatically validates the token on non-safe requests (POST, PUT, DELETE, PATCH) and rejects requests with invalid or missing tokens with a 403 Forbidden response.
Configuration Options
You can customize the middleware:
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 }); }, });
Trusted Origins
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$/, });
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), move the CSRF middleware to a layout route that wraps only your UI routes.
Install using
bunx shadcn@latest add @remix-utils/middleware-csrf-token.This depends on
@oslojs/crypto,@oslojs/encoding, and React Router.The CSRF Token middleware protects your application from Cross-Site Request Forgery attacks using a token-based approach where a random token is stored in a cookie and must be included in form submissions.
To use it, add it to the
middlewarearray in yourapp/root.tsxfile:Use the
getCsrfTokenfunction in your root loader to retrieve the token:You can use this with the
AuthenticityTokenProviderandAuthenticityTokenInputcomponents fromremix-utils/csrf/react:Then in your forms:
The middleware automatically validates the token on non-safe requests (POST, PUT, DELETE, PATCH) and rejects requests with invalid or missing tokens with a 403 Forbidden response.
Configuration Options
You can customize the middleware:
Trusted Origins
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:
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), move the CSRF middleware to a layout route that wraps only your UI routes.
Author
Sergio XalambrÃ