Search code examples
node.jsexpresscsrfmiddleware

Express js middleware not working when error is passed alongside ,req,res and next


So , I am trying to implement CSRUF in express and I want to have custom errors thrown instead of the default error handling of the middleware CSRUF example here. The CSRF implemntetion is working correctly and when the token is invalid,an error is thrown in console and a response with a 403 status is send to browser. I do not want the error to be handled by default. When I create a custom error handler middleware as below,

 function (err,req, res, next) {
    console.log("reached")
    if (err.code !== 'EBADCSRFTOKEN') return next(err)

    console.log("Not working")
    // handle CSRF token errors here
    res.status(500)
    res.send('form tampered with')
}

It appears that the middlware is not being implemented as the default error for CSRUF is being thrown.

Intrestingly,I noticed that when i have a custom middeware with an err parameter,the middleware appears to be ignored by the app. Example(This works)

 function (req, res, next) {
     console.log("This is some middleware") //Console outputs
      next()
   
}

However,When I add a err or error parameter to the function as below,it appears as though the middleware is not being used

function (req, res, next) {
         console.log("This is some middleware.Err parameter has been passed") //Nothing is output to console
         next()
    }

I have read the Express error handling documentation and done as required but i still face the error,What could be the issue and how do i handle such.


Solution

  • I finally figured it out. When I place the error handler middleware just after the CSRUF everything works i.e

    app.post(route,middleware1,errorhandler,(req,res)={
    //Any errors from middleware1 will now be catched by the errorhandler instead of the default error handler
    //Some code here
    })
    

    The location of the errorhandler appears to play a big role