title: Best way to debug 'Can't set headers after they are sent' error in Express / Node.js?
body: <p>I'm trying to debug the dreaded <code>Can't set headers after they are sent</code> error in a node.js Express application. Specifically, I'm using the <a href="https://github.com/LearnBoost/knox" rel="noreferrer">knox</a> library to talk to s3. </p>
  
  <p>Roughly, I have this Express handler, using a global instance of a knox s3client:</p>
  
  <pre><code>function foo(req, res) {
      //Region A
      var s3req = global.s3client.get('foo').on('response', function(s3res){
          //Region B
          res.set('content-length', s3res.headers['content-length']); //This will fail
          s3res.on('data', function(chunk){
              res.write(chunk);
          });
      });
      //Region C
      s3req.end();
  }
  </code></pre>
  
  <p>If I set any header or status code on <code>res</code> in Region A, everything works fine. If I try any of that in Region B, I get the "Can't set headers after they are sent" error. Note that I want to set headers on <code>res</code>, not <code>s3res</code></p>
  
  <p>Presumably <code>response.writeHead</code> is being called or triggered somewhere before the on response callback of the knox s3client is being called. Is there some debug flag or other way to get Node to spit out when/where writeHead has been called? Node 0.10 adds a <code>response.headersSent</code>, but it would be prohibitively hard to fill my code and all 3rd party libraries with a check of this flag to figure out where this is getting called. Or is there someway else to figure out this problem?</p>