Advanced Node and Express: Create New Middleware

Hey there.

I don´t understand how this code works. So, this function is created:

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
};

And then is used as parameter in here:

app
 .route('/profile')
 .get(ensureAuthenticated, (req,res) => {
    res.render(process.cwd() + '/views/pug/profile');
 });

When “ensureAuthenticated” is used in “app.get”, is the “next()” inside it calling res.render() when a user is authenticated?
What confuses me is that if the function does not have a route, what happens when we use “next()”? What can be the next matching route if there isn´t one?
Also, when this function is inside the “get”, is not called (I mean, I’m not doing “ensureAuthenticated()” . Is it checking if a user is authenticated?

Sorry if my explanation may not be clear, as I am confused myself…

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36

Challenge: Create New Middleware

Link to the challenge:

Never mind you have not provided the code for the function isAuthenticated().
With the given information and the way the function is used I confirm that this is an authentication test.

Means:

  1. The user sends a get-request to the given route (/profile → for example www.somepage.de/exampleProfile → /exampleProfile = /profile in this case)
  2. Node.js/Express will not directly respond with the /views/pug/profile but will execute the middleware-function (isAuthenticated()) first.
  3. If isAuthenticated() returns “true” Node.js/Express will continue to process the request.
    If isAuthenticated() returns “false” Node.js/Express will redirect the user to “/”.

So in this case “Next()” is used to tell Node.js/Express to go on processing the request.

1 Like

It might also be worth checking out the docs.

2 Likes

Thank you so much for confirming this!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.