Search code examples
node.jsexpresscsrfnode.js-connect

Express handling CSRF error: can I redirect to a custom error page?


How can I implement a custom error handler in Express using CSRF middleware after users click the back button in the browser and resubmit the form? By default Express return a 403 page with lots of stack traces. I want to replace it by for example redirecting user to a custom error page. How can I do that?


Solution

  • Here are some examples of writing custom error handlers in Express: https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

    Here are the custom error handlers I use: Error handling in an Express route

    You might also want to consider modifying connect to return a different code than 403 when CSRF fails. You can change it here: https://github.com/senchalabs/connect/blob/master/lib/middleware/csrf.js#L82

    You might choose 428 Precondition Required. The full list is here: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

    That way, you could have a special message shown only for CSRF failures.