title: Scope of middleware functions in express.js
body: <p>I'm learning express.js / node.js and have a good but not excellent understanding of the javascript prototype model. Hence, I'm a bit confused on the way middleware can be stacked in express.js's routing mechanisms.</p>
  
  <p>Say we have this <a href="http://expressjs.com/guide.html#route-middleware" rel="noreferrer" title="Source">code</a></p>
  
  <pre><code>function andRestrictTo(role) {
      return function(req, res, next) {
         req.authenticatedUser.role == role
             ? next() : next(new Error('Unauthorized'));
     }
  }
  
  app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){
      res.send('Deleted user ' + req.user.name);
  });
  </code></pre>
  
  <p>Since andRestrictTo(role) returns a middleware, it get's executed in the routing chain - I got that. However:</p>
  
  <ol>
  <li><p>Where does the req, res, next parameters come from in the returned function? I guess that the "chain" is somehow queuing it and assings the parameters, but this is a bit too vague for a deeper understanding ...</p></li>
  <li><p>What is happening with the Error that is raised as next's parameter? Does an error simply break the middleware chain?</p></li>
  <li><p>If I would want to package the restriction mechanism to a separate file / module (like a security framework), how would that be done?</p></li>
  </ol>
  
  <p>It would be cool if someone could point out the basic idea :)  </p>