node.jsexpressmiddlewarenode.js-connect

How do I access res.locals after calling app.router?


I am creating the middleware to be called after app.router and I need to access the data that was stored in res.locals object by the route middleware and route handler.

//...
app.use(app.router);
app.use(myMiddleware);
//...

app.get('/', function(req, res) {
    res.locals.data = 'some data';
});

function myMiddleware(req, res, next) {
    if (res.locals.data)
        console.log('there is data');
    else
        console.log('data is removed'); // that's what happens
}

The problem is that all properties of res.locals become empty after app.router.

I tried to find the place where express or connect cleans res.locals to somehow patch it but so far I can't find it.

The only solution I see at the moment is to abandon the idea of putting this logic in a separate middleware and put it in route-specific middleware, where res.locals is available, but it will make the system much more interconnected. Also I have many routes where route middleware does not call next (when res.redirect is called), so I will have to do many changes to make it work. I'd very much like to avoid it and put this logic in a separate middleware, but I need to access the data that was stored in res.locals.

Any help really appreciated.


Solution

  • You can possibly bind it before, but have it act after. The logger middleware is an example of this.

    app.use(express.logger('tiny'));
    app.use(myMiddleware);
    app.use(app.router);
    
    function myMiddleware(req, res, next) {
        var end = res.end;
        res.end = function (chunk, encoding) {
            res.end = end;
            res.end(chunk, encoding);
    
            if (res.locals.data)
                console.log('there is data');
            else
                console.log('data is removed');
        };
    
        next();
    }
    
    app.get('/', function (req, res) {
        res.locals.data = 'some data';
        res.send('foo'); // calls `res.end()`
    });
    

    Requesting / results in:

    GET / 200 3 - 6 ms
    there is data
    GET /favicon.ico 404 - - 1 ms
    data is removed