title: NodeJS Express: How to interrupt the routing from outside the middleware/router?
body: <p>I implemented a very simple middleware  to check the permissions for the user:</p>
  
  <p><strong>app.js</strong>  </p>
  
  <pre><code>...
  var security = require('./lib/security');
  app.use(security.init);
  ...
  </code></pre>
  
  <p><strong>lib/security.js</strong></p>
  
  <pre><code>var session;
  var request;
  var response;
  
  function init(req, res, next) {
    request = req;
    response = res;
    session = req.session;
    next();
  }
  
  function adminRequired(){
    if (!isAdmin()){
      response.redirect('/login');
      response.end();
      return true;
    }
    return false;
  }
  ...
  </code></pre>
  
  <p>The best way I found to interrupt the flow is the following:</p>
  
  <p><strong>routes/mycontroller.js</strong> </p>
  
  <pre><code>router.get('/', function(req, res, next) {
    if(security.adminRequiredHtml()){return;} // now it actually interrupt the execution
    res.render('admin',{});
    res.end();
  });
  </code></pre>
  
  <p>However, I would like to use it like this:</p>
  
  <p><strong>routes/mycontroller.js</strong> </p>
  
  <pre><code>router.get('/', function(req, res, next) {
    security.adminRequiredHtml(); // &lt;- interrupt the request
    res.render('admin',{});
    res.end();
  });
  </code></pre>
  
  <p>It correctly perform the redirect, but the execution continues :(<br>
  I've tried a few solutions like but it doesn't really work:<br>
  <code>response.end()</code> -> close the output but continues the execution<br>
  <code>process.end()</code> -> it's too radical, terminates the execution but it also kill the server :(</p>
  
  <p>I've been thinking about using a <code>throw</code> but I don't know where to catch it and make it terminate gracefully (no stacktrace)</p>