Skip to content

Context gets lost in Express after using session middleware #29

Open
@nasooz

Description

@nasooz

Hi Forrest,

First of all, in my view cls is a wonderful peace of software. I just started using it and it solves lots of issues for me. Thank you for creating it and sharing it.

This is actually a questing rather than an issue. I've successfully integrated cls in an Express 4 application but after adding session middleware I started experiencing issues. To be more specific, the context gets lost. The code I've got is very similar to the following:

var express = require('express');
var session = require('express-session');   
var cls = require('continuation-local-storage');

var ns = cls.createNamespace('contextNamespace');
var app = express();

app.use(function(req, res, next) {
    ns.bindEmitter(req);
    ns.bindEmitter(res);

    ns.run(function() {
        next();
    });
});

app.use(function(req, res, next ) {
    // context is available
    var namespace = cls.getNamespace('contextNamespace');
    next();
});

// this is the critical session middleware
app.use(session({ resave: true, saveUninitialized: true, secret: 'someSecret', store: sessionStore }));

app.use(function(req, res, next ) {
    // context is lost
    var namespace = cls.getNamespace('contextNamespace');
    next();
});

As per the comments in the code above, the content gets lost for all middleware after app.use(session());

I went through all open and closed issues and I gather that in this kind of situations ns.bind() can be used but I don't quite understand how. So, I was wandering if you could give me some directions as to how to approach and solve this issue?

Thank you in advance.

I've got one other minor note. In the very first code example in your README.md, you have session.set('user', user); which doesn't seem to be enclosed in a session.run(). Is this OK or my understanding of cls is still too shallow?

Cheers,

Nasko.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions