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

Where does userId come from?

Hi, in the profile route where does in 'req.session.userId' where does userId come from?

router.get('/profile', (req, res, next) => {
  if (!req.session.userId) {
    const err = new Error('Not allowed');
    err.status = 403;
    return next(err);
  }
  User.findById(req.session.userId)
    .exec(function (error, user) {
      if (error) {
        return next(error);
      }else{
        return res.render('profile', {title: 'Profile', name: user.name, favorite: user.favoriteBook })
      }
    })
});

The req.session.userId is set when a user signs up or when a user logs into the app. You are basically taking the id property from the user and setting it as a property on req.session. See example below:

router.post('/login', (req, res, next) => {
    User.login(req.body.email, req.body.password, (err, foundUser) => {
        if(err || !foundUser) {
            const err = new Error('User not found.');
            next(err);
        } else if(foundUser) {
            req.session.userId = foundUser.id;
            res.redirect('profile');
        }
    });
});

2 Answers

Thanks so much for the response, so basically it's a variable?

It's more of a property on a session object like this:

req: {
    session: {
        userId: "acbd1234"
    }
}

If you found my answer useful, please mark it as the accepted answer, thanks!

ahhhhh...I get it!! Thanks so much Bryon!!