Skip to content

Instantly share code, notes, and snippets.

@jeffwhelpley
Created July 12, 2015 02:06
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffwhelpley/056e012544c631438ad2 to your computer and use it in GitHub Desktop.
Save jeffwhelpley/056e012544c631438ad2 to your computer and use it in GitHub Desktop.
playing nice: continuation-local-storage, hapi.js and pm2

I had a lot of issues trying to get continuation-local-storage (cls) working on a hapi.js app with pm2 in cluster_mode. Long story short, my mistake was wrapping cls around my server.start() when I should have been running it in a request handler. Here is the code you should use to get all this working:

var cls = require('continuation-local-storage');
var ns = cls.createNamespace('mySession');

var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });

// make sure this is the very first handler you add to the server
server.ext('onRequest', function (request, reply) {
  ns.bindEmitter(request.raw.req);
  ns.bindEmitter(request.raw.res);
  ns.run(function () { reply.continue(); });
});

server.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment