87

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?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
piggyback
  • 9,034
  • 13
  • 51
  • 80

4 Answers4

213

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)

Stickley
  • 4,561
  • 3
  • 30
  • 29
piggyback
  • 9,034
  • 13
  • 51
  • 80
  • 25
    Correct answer but just to precise, it is <%-JSON.stringify(user)%> that render the magic. – Pierre Maoui Jan 31 '14 at 11:29
  • 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... – NicholasFolk May 02 '15 at 22:30
  • 1
    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. – NicholasFolk May 02 '15 at 22:33
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

user732456
  • 2,638
  • 2
  • 35
  • 49
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, '\\\\') %>
0

This will work now in Express's latest version