Passing an object to client in node/express + ejs?

In Node.js:

res.render('mytemplate', {data: myobject});

In EJS:

<script type="text/javascript">
  var rows =<%-JSON.stringify(data)%>
</script>

SECURITY NOTE : Don’t use this to render an object with user-supplied data. It would be possible for someone like Little Bobby Tables to include a substring that breaks the JSON string and starts an executable tag or somesuch. For instance, in Node.js this looks pretty innocent…

var data = {"color": client.favorite_color}

but could result in a client-provided script being executed in user’s browsers if they enter a color such as:

"titanium </script><script>alert('pwnd!')</script> oxide"

If you need to include user-provided content, please see https://stackoverflow.com/a/37920555/645715 for a better answer using Base64 encoding

Leave a Comment