Sanitize Backbone.js Models to prevent XSS

This isn’t groundbreaking code, but you may find it useful to know how to take a step to prevent XSS attacks when implementing Backbone MV*. Some JavaScript frameworks automatically escape or sanitize the values being passed to the model. Backbone does not. However, the library it’s built on (Underscore.js) does provide an easy way to escape values.

First, in your Model, create your initialize() method, and in it, use the _.each method to iterate over the attributes object, passing the value to a method belonging to the Model named “sanitize”.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key)
      this.set(key, this.sanitize(val));
    }, this);
  }
});

Let’s add our sanitize() method. In this method, simply take in the string as a parameter, and return the escaped version of it, using Underscore’s _.escape method.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key) {
      this.set(key, this.sanitize(val));
    }, this);
  },
  sanitize: function (str) { 
    return _.escape(str) 
  } 

});

I recommend sanitizing in your model’s initializer so that you ensure it’s properly scrubbed before calling Model.save() and sending nasty XSS or SQL injection to your server. Also, sanitize anywhere you update the model or allow edits to the model.

I hope you found this post useful. If you have anything to add or find any problems, let me know.