Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 862
Rafał Sobota Avatar asked Jul 22 '12 11:07

Rafał Sobota


3 Answers

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

  • Domains in node 0.8

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(); }); 
like image 166
Jonny Buchanan Avatar answered Sep 23 '22 01:09

Jonny Buchanan


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.

like image 38
Christopher Currie Avatar answered Sep 24 '22 01:09

Christopher Currie


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.

like image 42
Matt Smith Avatar answered Sep 23 '22 01:09

Matt Smith