Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 565
Yitong Zhou Avatar asked Dec 16 '12 18:12

Yitong Zhou


People also ask

How do you use cookies in Express?

Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the user's actions. Now to use cookies with Express, we will require the cookie-parser.

How can Express set a cookie on the client?

In order to correctly set cookies accessible on the client just use a snippet like the following: res. cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false});

Does Express-session use cookies?

Here is a simple explanation: - A user session can be stored in two main ways with cookies: on the server or on the client. express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.


1 Answers

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().

like image 126
theabraham Avatar answered Oct 18 '22 00:10

theabraham