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 User Authentication With Express and Mongo Improving the App with Custom Middleware Writing Custom Middleware

Robert Cooper
Robert Cooper
22,704 Points

Unnecessary "if" statement conditional?

In the following code block, isn't it redundant to have req.session in addition to req.session.userId? If req.session.userId evaluates to true, that means that there is a session and req.session is also true.

function loggedOut(req, res, next) {
  if (req.session && req.session.userId) {
    return res.redirect('/profile');
  }
  return next();
}

1 Answer

In the code block provided, the use of req.session first is to prevent front a script error in checking an undefined property.

If req.session doesn't exist, it becomes unsafe to try and access a property against undefined. Essentially you would be doing this:

var request = undefined;

console.log(request.sessions.userId) 

You wouldn't do this as request is not an object, nor does it have a property called session

Robert Cooper
Robert Cooper
22,704 Points

Awesome, thanks for the explaining Joe. That makes a lot of sense.

Glad I could help :]