HTTP: Cannot read property 'Symbol(asyncId)' of null

  • Version: 8.0.0 - latest
  • Platform: Darwin 16.6.0 Darwin Kernel Version 16.6.0: Fri Apr 14 16:21:16 PDT 2017; root:xnu-3789.60.24~6/RELEASE_X86_64 x86_64
  • Subsystem: http

It appears like the addition of async_hooks API into the http module (commit 4a7233c) causes an edge case to occur with 'write after end'. Here is a stack trace:

TypeError: Cannot read property 'Symbol(asyncId)' of null
    at write_ (_http_outgoing.js:636:24)
    at ServerResponse.write (_http_outgoing.js:630:10)
    at Immediate.setImmediate [as _onImmediate] (/test.js:10:7)
    at runCallback (timers.js:800:20)
    at tryOnImmediate (timers.js:762:5)
    at processImmediate [as _immediateCallback] (timers.js:733:5)

This is an unhandled exception, thrown all the way up to OutgoingMessage.prototype.write, causing crashes when used with streams in some cases. It appears like msg.socket[async_id_symbol] is causing the error due to msg.socket being null. I have slimmed down the code into as bare as I could. Here is my code:

var http = require('http');

// This code crashes the process
http.createServer((req, res) => {
    res.on("error", (err) => console.error("res had error:", err));
    
    res.write('hello');
    res.end();
    setImmediate(() => {
        res.write('world')
    })
}).listen(9000);

// This code works as expected
http.createServer((req, res) => {
    res.on("error", (err) => console.error("res had error:", err));
    
    res.write('hello');
    res.end();
    res.write('world')
}).listen(9001);

The second block works as intended (emits the error event). It appears like this bug occurs in all versions after v8.0.0.