Express and ejs <%= to render a JSON
Asked Answered
B

4

90

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?

Buffoon answered 9/12, 2012 at 14:29 Comment(0)
B
218

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)

Buffoon answered 9/12, 2012 at 14:32 Comment(3)
Correct answer but just to precise, it is <%-JSON.stringify(user)%> that render the magic.Congresswoman
Is the eval function actually used, or are you implying that what results is similar to if eval was called. I'm curious, because as we all know, eval is...Dialectology
Ok, so because of my curiosity, I dived into it and discovered that it does in fact use eval(). I should also add that I know it's an often parroted saying and eval isn't necessarily evil, just easily misused. Had to mention that before I inspired some wrath among the masses.Dialectology
L
6

Attention!

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

Pass variables to JavaScript in ExpressJS

Lewes answered 21/2, 2016 at 9:30 Comment(0)
T
2

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, '\\\\') %>
Toffic answered 24/11, 2020 at 1:38 Comment(0)
N
0

This will work now in Express's latest version

Nerta answered 5/2, 2022 at 16:8 Comment(1)
Which version ?Cicatrize

© 2022 - 2024 — McMap. All rights reserved.