Express doesn't pass object to the view


Im trying to send a user object from passport to the browser, but all I get is window.user undefined in the console.

In the route I've checked the object with console.log("USER:"+JSON.stringify(req.user, null, 4))

and I get the proper output:

    "emails": [
    "nick": "nickname",
    "identifier": "76561197990749921",
    "points": 140

While trying to send it with res.render('index', {user: req.user}); I cant retrieve it from the window object. But when i send some property for example res.render('index', {user: req.user.points}); it is attached to window.user as its supposed to... On the other hand while trying to send req.user.nick its also not attached to window. What may be the problem?

Problem courtesy of: mjanisz1


render does not preserve objects. The object you pass the .render function gets used as string-macros for your template, so if your index template has a {{ user }} or <% user %> in it (syntax depending on the templating engine you picked), then it'll write the string that your user content coerces to into your file.


<p>{{ user }}</p>


res.render('index', {user: {"name": "monkey"}});


<p>{"name": "monkey"}</p>

And that's text, not a JavaScript object. Of course we could make sure the string goes into a script block:


<script> var user = {{ user }}; </script>


res.render('index', {user: {"name": "monkey"}});


<script> var user = {"name": "monkey"}; </script>

And now we can suddenly use it in the rest of our on-page JavaScript.

Solution courtesy of: Mike 'Pomax' Kamermans


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.