Backbone and Express Forgery Protection (csrf)

août 12th, 2013

I had a problem getting Node.js/Express playing nice with Backbone. It was not sending the csrf authenticity token embedded in the page when it sent create/update/delete requests, and Express was destroying the session when it detected the invalid request.

Here is all the javascript it took to get Backbone to include the token with all requests:

initialize: function() {
  /* alias away the sync method */
  Backbone._sync = Backbone.sync;
  // override original sync method to make header request contain csrf token
  Backbone.sync = function(method, model, options, error){
       options.beforeSend = function(xhr){
           xhr.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-param']").attr('content'));
       /* proxy the call to the old sync method */
       return Backbone._sync(method, model, options, error);

also you need to include connect’s csrf middleware in express3 configuration:

// setup csrf (implement to backbone)

// routes should be at the last

Note that this depends on the meta tags being present, which require you to add csrf-param in your meta tag view for the page (put it in the head).