I already asked this question to the author of csurf (Douglas Wilson) via Github Issues and he suggested to create a new post on stackoverflow.
The original issue is here: https://github.com/expressjs/csurf/issues/161
My situation is: I have some apis in express (post, put, get and delete) also with path params. Some examples: DELETE /api/users/2376213786213 POST /api/users . (with a body) and so on
I want to use csurf, but I also want to catch when someone call an api with an empty path param and return a 404. In short, If you call DELETE /api/users/ (with an empty id as path param) I want to return 404, otherwise if you call DELETE /api/users/12121 I want to handle the csrf token and return 403 if not valid. Is it possible? How?
I created a middleware to handle csrf like in the official csurf's example:
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('form tampered with')
})
And after this middleware, I created another one to handle 404, nothing special.
However, this api DELETE /api/users/ (with an empty id as path param) is trapped by the first middleware and return 403, instead of 404.
How can I fix this?
Thank you.