How does Express/Connect middleware work?

I am learning Node.js, and I have read some tutorials, like The Node Beginner Book for learning the core funcionality. But the more I read some examples, the more doubts I start collecting.

On the further example, obtained from a tutorial, we can see that for a CRUD 'read' request for key /documents/titles.json, we are returning a value:

app.get('/documents/titles.json', loadUser, function(req, res) {
  Document.find({ user_id: req.currentUser.id },[], { sort: ['title', 'descending'] },
  function(err, documents) {
     res.send(documents.map(function(d) {
        return { title: d.title, id: d._id };
     }));
  });
});

On this example, the function loaduser() is used for authentication purposes:

function loadUser(req, res, next) {
   if (req.session.user_id) {
      User.findById(req.session.user_id, function(err, user) {
         if (user) {
            req.currentUser = user;
            next();
         } else {
            res.redirect('/sessions/new');
         }
      });
   }
}

What I don't understand is:

  1. I suppose that node.js, before start executing the app.get, it goes to loaduser function. loadUser() function has three parameters: req,res,next, but I don't see, at least, how you pass from app.get() the "req" parameter to loadUser(). From where does it come?
  2. Inside loadUser() function, when you execute next(), it means that the function app.get()" can continue its procedure, but this req.currentUser = user, is the same req that is used on app.get() function?
  3. Inside loadUser() function, when you execute res.redirect() code, automatically breaks the procedure on app.get() function, right? it looks like it doesn't return to Document.find().

The questions you've asked are about the Express framework internals specifically:

  1. When you call app.get(route, loadUser, final) Express will make a stack (array) with the loadUser and final function functions and it will know that when you call next it should execute the following function in the stack with the same req and res params.

  2. When you call next it will just pass to the next function in the middleware stack.

  3. Since you call res.redirect and you don't call return, it won't pass to the next function in the stack (the one with Document.find).

Resources:

http://howtonode.org/getting-started-with-express

I think in order to be comfortable with this you need get familiar with idea of middleware and how it's used in connect framework.

I've found few articles where this subject explained well enough. Take a look there:

http://howtonode.org/connect-it and here http://stephensugden.com/middleware_guide/

the main idea is you have a set of layers and each time when new request arrives it goes through each level and on each level you can decide what to do with that. You can stop at some level, do something and return response or you can pass it to the next layer