I\'m writing a small web app with Node.js using the Express framework. I\'m using the csrf middleware, but I want to disable it for some requests. This is how I include it i
There are several possible approaches. You basically need to understand what is the simplest and most correct rule to decide whether or not to use the csrf middleware. If you want csrf most of the time, except for a small whitelist of request patterns, follow the example in this answer I have about conditional logging middleware (copied below for convenience).
var express = require("express");
var csrf = express.csrf();
var app = express.createServer();
var conditionalCSRF = function (req, res, next) {
//compute needCSRF here as appropriate based on req.path or whatever
if (needCSRF) {
csrf(req, res, next);
} else {
next();
}
}
app.use(conditionalCSRF);
app.listen(3456);
Another approaches could be only using the middleware on a certain path like app.post('/forms/*', express.csrf()). You just want to find an expressive way to make it clean when the middleware will or will not be used.