Question

I'm using Sails 0.9.8 to back a small e-commerce site. Currently, I have sessions expire after 30 minutes. When a user has the site open for longer than that (perhaps in the background), they get the expected Forbidden error on submitting which spits out the node stack error (csrf expired). While this is developer-friendly, I'd prefer to show them some custom error page or even refresh the page.

Is there any solution to this for v0.9.8 or is upgrading to v0.10 the easier route?

Was it helpful?

Solution

You can do it in v9, although it's a little non-obvious. The trick is to turn your default 500-error handler, which is included by Sails as a fallback Express middleware, into a true Express error handler. To do that, simply change the function signature in your app's config/500.js file from:

function serverErrorOccurred(errors, req, res)

to

function serverErrorOccurred(errors, req, res, next)

Express interprets any middleware with four parameters as an error handler, so when the CSRF code passes its error along, this method will run. Now, it's up to you inside the serverErrorOccurred method to determine whether the error is coming from a missing CSRF token; I'd start by checking errors.status to see that it's a 403, then check req.url and req.method to determine what the user was trying to do. Have fun!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top