Search code examples
node.jsexpresscsrfnode.js-connect

Ajax-Compatible middleware for express/connect


As it says in the title, I'm looking for a middleware for express.js or connect that will enable me to make csrf-safe requests.

The csrf-middleware in connect creates a new token per request, which makes POST-requests over Ajax not very easy.


Solution

  • If you want to only create a new CSRF token per session instead of per request or something, you could always take advantage of the fact that that Connect's csrf middleware lets you pass in your own token generation function. For example:

    connect.csrf(function (req) {
      if (!req.session['myCsrfToken']) {
        req.session['myCsrfToken'] = ... // generate token somehow
      }
    
      return req.session['myCsrfToken'];
    });