Last Updated: February 25, 2016
·
6.272K
· regality314

Using Domains With Express

Setting up express to use the new node.js domains can be a bit tricky, but this little snippet will do the trick:

var app = express.createServer();

// a bunch of your middleware...
app.use(setupDomains);
// the rest of your middleware...

var domain = require('domain');
function setupDomains(req, res, next) {
  var reqd = domain.create();
  domain.active = reqd;
  reqd.add(req);
  reqd.add(res);
  reqd.on('error', function(err) {
    req.next(err);
  });
  res.on('end', function() {
    console.log('disposing domain for url ' + req.url);
    reqd.dispose();
  });
  reqd.run(next);
}

This way if anything throws an error that was called from an express route, but wasn't part of the same callstack, the error will return to the error handler for that route, instead of tearing down the entire process.

There are two caveats.

The first is that it appears to break if you use setupDomains prior to sessions.

The second is to be aware that if any io, such as file or database connectors, is set up and attached to the request, it will be disposed with the request and everything will go to hell. So be sure to use a separate domain when opening any io that will last longer than the request.

4 Responses
Add your response

This is pretty useful. Thanks!

Also.. according to this.. domain.dispose is being deprecated: https://github.com/joyent/node/issues/5018

And according to the domain docs, you should kill the process when an error is caught: http://nodejs.org/api/domain.html#domain_domain

over 1 year ago ·

Not from there, but looks like they came to a similar conclusion.

over 1 year ago ·

How exactly would you "use a separate domain when opening any io that will last longer than the request." ?

over 1 year ago ·