Backbone.js and XSS/HTML escaping

hupf picture hupf · Sep 25, 2012 · Viewed 13.8k times · Source

I'm building a Backbone.js application and am wondering what's the best way to deal with XSS respectively HTML escaping when using Backbone.js.

In the basic Todos example application from the official Backbone.js documentation, the data is not escaped. Since this data is used in the template to render the todo entries, it is possible to execute Javascript code by entering the following text (can be reproduced at the link above):

"><script>alert('xss');</script>

When using a REST server as storage backend, this XSS is persistent for every user.

How do you solve this problem?

My idea is to escape the data on the server, so the then returned data is safe to be used in a template. Do I then have to always use wait: true, to make sure no unescaped data is rendered? And for editing, add another attribute with the unescaped data, that can then be used to fill the textfield using .val()?

Or do you do none of this and escape the data on the client, before rendering the template?

Answer

Rob W picture Rob W · Sep 25, 2012

The Todo example is not the cleanest example. It uses underscore's template engine, as follows:

<input class="edit" type="text" value="<%= title %>" />

To correctly escape the HTML, use <%- instead of <%=:

<input class="edit" type="text" value="<%- title %>" />