How to use Node.js 0.8.x domains with express? How to use Node.js 0.8.x domains with express? express express

How to use Node.js 0.8.x domains with express?


This set of slides on Speaker Deck gives a succinct overview:

Express middleware code from the slides:

var createDomain = require('domain').create;app.use(function(req, res, next) {  var domain = createDomain();  domain.on('error', function(err) {    // alternative: next(err)    res.statusCode = 500;    res.end(err.message + '\n');    domain.dispose();  });  domain.enter();  next();});


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.


I've had good luck replacing the stock

var app = express.createServer();

with:

var domainCreate = require('domain').create;var app = express.createServer(function (req, res, next) {    var domain = domainCreate();    domain.run(next);});

Then in your middleware you can add properties to process.domain or add additional error handling.