31

I have been using expressjs and mongostore for session management. Following is the code to configure store in expressjs,

app.configure(function(){
    app.use(express.session({
        secret: conf.secret,
        maxAge: new Date(Date.now() + 3600000),
        cookie: { path: '/' },
        store: new MongoStore(conf.db)
    }));
});

I had mentioned the cookie path in the above code. But it sets the cookie in sub.domain.com instead of .domain.com. How do i achieve this?

Raja
  • 3,477
  • 12
  • 47
  • 89
  • 2
    Remember that setting cookies to main domain name will cost you additional network traffic. See [Best Practices for Speeding Up Your Web Site](http://developer.yahoo.com/performance/rules.html#cookie_free) from Yahoo guys. – esengineer Nov 02 '12 at 11:35

3 Answers3

42

Try to use the following link to configure.

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });

Link : http://expressjs.com/api.html#res.cookie

arulmr
  • 8,620
  • 9
  • 54
  • 69
AmirtharajCVijay
  • 1,078
  • 11
  • 12
42

configure it like this:

app.use(express.session({
    secret: conf.secret,
    cookie: { domain:'.yourdomain.com'},
    store: new MongoStore(conf.sessiondb)
}));
metis
  • 444
  • 5
  • 2
  • 5
    Is it possible to set a cookie for more than one domain? ex : cookie: { domain:'.yourdomain1.com','yourdomain2.com}, –  Feb 19 '20 at 13:06
  • I just tried `example.com` and it worked. Is there any difference in adding a `.` in there? – Esqarrouth Mar 26 '21 at 11:44
1

This won't work, it throws error. Error: Most middleware (like session) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

app.use(express.session({
    secret: conf.secret,
    cookie: { domain:'.yourdomain.com'},
    store: new MongoStore(conf.sessiondb)
}));

I have a reference link, from where you can take help to set domain in cookie https://flaviocopes.com/express-cookies/

aadilraza339
  • 103
  • 3