Disable csrf validation for some requests on Express Disable csrf validation for some requests on Express express express

Disable csrf validation for some requests on Express


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.


Since Express middleware executes in order, you could always put your statements above the csrf() statement in the code.

Like this:

app.get '/ping', (req, res) -> res.status(200).end()app.use csrf()

Express will return before your csrf token gets set. For very small numbers of endpoints (I just have one that fits this category), I've found this to be a cleaner solution.

Also, as of this writing, the code for the above answer would look like this:

customCsrf = (req, res, next) ->  if req?.url isnt '/ping'    return csrf()(req, res, next)  else    return next()app.use customCsrf

That extra (req, res, next) tripped me up for awhile, so hope this helps someone.


dailyjs.com has a good article about csrf and express. It basically works like this:

use the csrf middleware:

app.configure(function() {  // ...  app.use(express.csrf());  // ..});

create a custom middleware that sets the local variable token to the csrf value:

function csrf(req, res, next) {  res.locals.token = req.session._csrf;  next();}

use your custom middleware in every route you want:

app.get('/', csrf, function(req, res) {  res.render('index');});

in your form create a hidden field that holds the csrf value:

form(action='/contact', method='post')  input(type='hidden', name='_csrf', value=token)