Express and ejs <%= to render a JSON

JavascriptJsonExpressEjs

Javascript Problem Overview


In my index.ejs I have this code:

var current_user = <%= user %>

In my node I have

app.get("/", function(req, res){
    res.locals.user = req.user
    res.render("index")
})

However, on the page I obtain

var current_user = [object Object]

and if I write

var current_user = <%= JSON.stringify(user) %>

I obtain:

var current_user = {&quot;__v&quot;:0,&quot;_id&quot;:&quot;50bc01938f164ee80b000001&quot;,&quot;agents&quot;:...

Is there a way to pass a JSON that will be JS readable?

Javascript Solutions


Solution 1 - Javascript

Oh that was easy, don't use <%=, use <%- instead. For example:

 <%- JSON.stringify(user) %>

The first one will render in HTML, the second one will render variables (as they are, eval)

Solution 2 - Javascript

Attention!

If the user can be created through API calls, <%- would leave you with serious XSS vulnerability. Possible solutions can be found here:

https://stackoverflow.com/questions/16098397/pass-variables-to-javascript-in-expressjs/16098699#16098699

Solution 3 - Javascript

if like me your object can include an escaped character such as / or " then use this more robust solution

var current_user = <%- JSON.stringify(user).replace(/\\/g, '\\\\') %>

Solution 4 - Javascript

This will work now in Express's latest version

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpiggybackView Question on Stackoverflow
Solution 1 - JavascriptpiggybackView Answer on Stackoverflow
Solution 2 - Javascriptuser732456View Answer on Stackoverflow
Solution 3 - JavascriptCookie_Wookie_7View Answer on Stackoverflow
Solution 4 - JavascriptTrainerCheeseView Answer on Stackoverflow