Answer the question
In order to leave comments, you need to log in
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>
<script>
var obj = JSON.parse("{{ json | safe }}");
</script>
{userinput: "</script><script>alert('hacked')//", ...};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question