That’s it! The form is now protected from CSRF attacks with csurf
. What happens in the case of an invalid CSRF token or none in a user request? CSURF will sense an error. It’ll respond with this ugly error message with a stack trace from the server:
ForbiddenError: invalid csrf token at csrf (/home/ccuser/workspace/csurftest/node_modules/csurf/index.js:112:19) at Layer.handle [as handle_request] …
To improve the error message, we can create a custom error message for invalid CSRF tokens. We do this by creating another middleware function to app.js using app.use()
with four arguments: err
, req
,res
, and next
. We can check if there is an invalid CSRF token by checking if err.code
is equal to 'EBADCSRFTOKEN'
, an error code defined by the CSURF module. If there is, we can return a response status of 403
with res.status()
. Then use the res.send()
function to send an error message describing the CSRF token mismatch.
app.use((err, req, res, next) => { if (err.code === 'EBADCSRFTOKEN') { res.status(403) res.send("The form was tampered with!") } else { next(); } })
Finally, if there is no error code, then we can continue using the next()
function. Let’s add this error handling to our code!
If you’d like to run the application, type node app.js
into the bash Terminal and then refresh the mini browser.
Instructions
Inside app.js, create a new middleware function using the app.use()
function that takes four arguments: err
, req
, res
, and next
using ES6 arrow syntax.
Press the Check Work button to check your work after each checkpoint.
Inside the middleware function, check whether there is an invalid token.
If it is invalid and set the response status to 403
with the text "The CSRF token is invalid"
.
Create an else
condition that exits the middleware function by calling the next()
function.