title: Manually injecting express app via `http.createServer` proxy
body: <p>I am currently authoring a component for a users sites which adds a number of resources to their server. For my part, I am wanting to use express, but the user could be using express themselves or some other web framework.</p>
  
  <p>Because I want this to just work out of the box, I was attempting to setup my express pipeline via proxying <code>http.createServer</code>. Injecting the pipeline this way seems to work reasonably well in cases where I handle the request, but it fails in cases where I let it fall through and execute the users callback (specifically, it says that the response headers have been sent already).</p>
  
  <p>Here is the sample I am working on. Any ideas?</p>
  
  <pre><code>var http = require('http');
  var express = require('express');
  
  var setupProxy = function setupProxy() {
      var app = buildApp();
  
      var oldCreateServer = http.createServer;
      http.createServer = function(callback) { 
          return oldCreateServer(function(req, res) {n
              app.apply(this, arguments);
  
              if (!res.finished) {
                  callback.apply(this, arguments);
              }
          });
      };
  };
  
  var buildApp = function buildApp() {
      var app = express();
  
      app.use('/test', function(req, res) {
          res.send('Hello World');
      });
  
      return app;
  };
  </code></pre>