Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Session Data - Middleware

In the last lesson (called "Authenticating the Username and Password") we made sure to keep session data only stored on the server, so the "UserId" is NEVER sent to the client (only a cookie is sent to the browser, containing the "sessionId").

router.post("/login",function(req,res,next){
  if(req.body.email && req.body.password){
    User.authenticate(req.body.email,req.body.password,function(error,user){
      if(error || !user){
        //error handling
      } else {

        // here we set the userId on the "req" object
        req.session.userId = user._id;

        return res.redirect("/profile");
      };
    });
  } else {
    //error handling
  }
});

Here, instead, Dave made available user's data in the response object, to get them inside the templates.

app.use(function(req,res,next){
  res.locals.currentUser = req.session.userId;
  next();
});

But this way we also make available the UserId to the client (storing it in the "res" object), isn't it a SECURITY ISSUE?