How to implement "login remember me" using cookies in Express.js?

21,034

Solution 1

res.cookie is actually a function with a signature of res.cookie(key, value, opts). You can use it to set a client's cookie values/options. On the other hand, req.cookies is an object that gives you the client's current cookie values. Here's an example using cookies to track page views:

var counter = 0;
app.get('/counter', function(req, res) {
    res.cookie('counter', ++counter);

    if (!req.cookies.counter) {
        res.send('This is your first visit!');
    } else {
        res.send('This is visit number '+ req.cookies.counter +'!');
    }
});

If you use the express.cookieSession() middleware, you can set application wide default cookie properties. For example, the cookie's maxAge property determines how many milliseconds in the future the cookie will expire, so here I set it to expire in one hour:

app.use(express.cookieParser());
app.use(express.cookieSession({ secret: 'secret', cookie: { maxAge: 60 * 60 * 1000 }});
// ... your middleware and routes

Otherwise, you could set the cookie options individually by passing an options object to res.cookie().

Solution 2

I suggest that your refer to the following question/answer. What your looking for is the below code. It allowed you to set the max age of each cookie.

if(remember){
    req.session.cookie.maxAge = 2628000000;
}
Share:
21,034
Yitong Zhou
Author by

Yitong Zhou

Loves coding.

Updated on July 09, 2022

Comments

  • Yitong Zhou
    Yitong Zhou almost 2 years

    I feel quite confused, do not understand what is the difference between res.cookie and req.cookies. And more strangely, I have found that if I do not set a cookie:

    //The value will be:
    req.cookies.uid=="undefined"
    //instead of:
    req.cookies.uid==undefined
    

    Why the express.js design the cookie like this?

    If I want to implement a "remember me" function while users trying to log in and set the cookie expire time to infinite or maybe a year, how should I use the cookie correctly?

    I have found that the cookieParser only support thing like this:

    express.cookieParser("secret")
    

    And does not support expire/maxAge setting.