How can I create Express/Connect middleware which wrap each request in its own domain?
UPDATE: The approach described below has been implemented in the connect-domain NodeJS module, which can be used in either Connect or Express applications.
As of Express 3, express.createServer
is deprecated, and its callback should be converted to a middleware. In the middleware, it's important to add the request and result objects to the request domain so that errors fired by them are handled by the domain error handler.
My middleware looks something like this:
var domain = require('domain');
app.use(function(req, res, next) {
var requestDomain = domain.create();
requestDomain.add(req);
requestDomain.add(res);
requestDomain.on('error', next);
requestDomain.run(next);
});
You can avoid adding the request and response to a request domain if you call http.createServer
from within a top-level domain, but the Domain docs seem to indicate that per-request domains are a best practice.
Note that the code above doesn't do any domain clean up actions, such as forcibly disposing the request domain. My middleware chooses instead to pass the error through the middleware stack again to be handled by specific error-handling middleware later on. YMMV.