Search code examples
javascripttemplatesunderscore.jscontent-security-policyunderscore.js-templating

How do I remedy Browser CSP errors when using underscore.js


I have been working on a web application for the past couple of years and have recently gone to make it more secure by adding Content Security Policy.

I have been able to remedy most of the issues I have found, but I have been unable to solve one remaining issue. CSP complains with an error message whenever templating occurs in underscore.js as I believe it makes use of a no-no; being the js code "new Function(...)".

I have seen other recommendations on the web, being basically:

  • Use an engine to precompile the template, eg Grunt-inline-template-compile This is useful for when you have your template strings inline, mine are all in the actual html in tags, so this wouldn't be possible without drastic content moving around.
  • Switch to another templating engine, this option would be more appealing to the previous but I am afraid it will break all the many lines of templating syntax of underscore and be a huge job in itself.

Are there any other options people are aware of?


Solution

  • Try setting the Content-Security-Policy header to unsafe-eval for scripts from your domain as a temporary workaround. http://content-security-policy.com/ Then move to a template engine such as Handlebars as soon as possible. You can have your templates in separate html files and compile them into javascript as part of your build. This gives you a nice separation between html and js as you develop but good performance in the browser for your users in the production version