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

Rafał Sobota picture Rafał Sobota · Jul 22, 2012 · Viewed 9.6k times · Source

How can I create Express/Connect middleware which wrap each request in its own domain?

Answer

Jonny Buchanan picture Jonny Buchanan · Jul 22, 2012

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();
});