Tuesday, 2 May 2017

How to populate req.user from cookies in each request with Express.js?

I want to implement a persistent login (i.e. "remember me") with client-side cookies. I think in Express.js (and Passport.js), this is usually done by sessions.

Instead, I set the rememberMe cookie after login with a long maxAge, and I want to call req.user = req.cookies.rememberMe in each request. For this, the best I can do is make a middleware and call it in every route, such as the following:

myMiddleware = function(req, res, next) {
    req.user = req.cookies.rememberMe;
    return next();
}

app.route('/page1')
    .get(myMiddleware, function(req, res) {
        // rest of the code that depends on req.user
        res.render('page1', { user: req.user })
    })
    .post(myMiddleware, function(req, res) {
        // ...
    })

app.route('/page2')
    .get(myMiddleware, function(req, res) {
        res.render('page2', { user: req.user })
    })
    .post(myMiddleware, function(req, res) {
        // etc.
    })

// ...

But it means repeating the call in every method, which makes the code ugly :) Can I instead define this function somewhere else so that inside each request, req.user will already be populated?

Thanks,



via jeff

No comments:

Post a Comment