D
D
Dmitry Shnyrev2017-04-19 10:39:56
JavaScript
Dmitry Shnyrev, 2017-04-19 10:39:56

How to pass a value to javascript in a template that is rendered on the server side?

How to correctly pass the object inside the script (on the frontend side) when rendering the template on the server side (express + nunjucks templates). The object contains user data, that is, it can contain anything. I serialize the object in JSON so that I can then substitute it into the script and parse it using JSON.parse. If output directly, then nunjucks html escaping is enabled and the resulting js is invalid. If you turn off escaping and output as is, then this is fraught with problems with XSS. For some reason, I couldn’t google a clear example for nodejs, although I know that the task is relevant and there are methods in other template engines (var a = {!JSENCODE(var)}, for example, in Visualforce). I found one way out, but so to speak, through another place - to output JSON as a normal escaped text in an html tag and then pull it out using innerHTML, and then parse. But maybe there is a more elegant way?
PS: The Internet mainly offers school examples that do not work from a security point of view

<script>
    var obj = {{ json | safe }}; 
</script>

or
<script>
    var obj = JSON.parse("{{ json | safe }}"); 
</script>

If json is
{userinput: "</script><script>alert('hacked')//", ...};

then it can end badly
without safe js inside it is escaped but the string becomes invalid for JS

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kulaeff, 2017-04-19
@kulaeff

You can try using data attributes on some html element, for example, on body.
Let's say json is like this:

{
    id: 1,
    title: 'blablabla'
}

then it will continue to parse it. Or you can split it into several data attributes:
<body data-id="1" data-title="blablabla">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question