Pass variables to JavaScript in ExpressJS

You could use this (client-side):

<script>
  var myVar = <%- JSON.stringify(myVar) %>;
</script>

You could also get EJS to render a .js file:

app.get('/test.js', function(req, res) {
  res.set('Content-Type', 'application/javascript');
  res.render('testPage', { myVar : ... });
});

However, the template file (testPage) would still need to have the .html extension, otherwise EJS won’t find it (unless you tell Express otherwise).

As @ksloan points out in the comments: you do have to be careful what myVar contains. If it contains user-generated content, this may leave your site open for script injection attacks.

A possible solution to prevent this from happening:

<script>
  function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
  }
  var myVar = JSON.parse(htmlDecode("<%= JSON.stringify(myVar) %>"));
</script>

Leave a Comment