title: Node.js use csurf conditionally with express 4
body: <p>I try to use csurf on just a few routes in my express app.
  that's the approach:</p>
  
  <pre><code>var express       = require('express');
  var session       = require('express-session');
  var csrf          = require('csurf');
  
  // some more stuff
  
  var csrfExclusion = ['/myApi','/unsecure'];
  
  var app   = express();
  
  var conditionalCSRF = function (req, res, next) {  
    if (csrfExclusion.indexOf(req.path) !== -1){
      next();
    }
    else{
      csrf();
    }
  });
  
  app.use(conditionalCSRF);
  </code></pre>
  
  <p>even tried:</p>
  
  <pre><code>var conditionalCSRF = function (req, res, next) {  
    if (csrfExclusion.indexOf(req.path) !== -1){
      next();
    }
    else{
      csrf(req, res, next);
      next();
    }
  });
  </code></pre>
  
  <p>and</p>
  
  <pre><code>var conditionalCSRF = function (req, res, next) {  
    if (csrfExclusion.indexOf(req.path) !== -1){
      next();
    }
    else{
      csrf();
      next();
    }
  });
  </code></pre>
  
  <p>But this gives me an error: Object # has no method 'csrfToken'</p>
  
  <p>How can I use csurf conditionally. The documentation only gives information to use it on all routes in the express app with</p>
  
  <pre><code>app.use(csrf());
  </code></pre>
  
  <p>But that's not what I want, I want to exclude some route...</p>
  
  <p>kindly... martin</p>
  
  <p><strong><em>UPDATE:</em></strong></p>
  
  <p>finally it works. I did the following:</p>
  
  <pre><code>app.use(function(req, res, next){
    if (csrfExclusion.indexOf(req.path) !== -1) {
    next();
  }
    else {
    csrf()(req, res, next);
  });
  </code></pre>
  
  <p>This adds the csrf middleware conditionally.
  But I really think it's kind of strange to call it like this: </p>
  
  <pre><code>csrf()(req, res, next);
  </code></pre>
  
  <p>I even do not get the syntax... </p>