Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Express - difference between req.cookies and req.session.cookie

I am trying to find out what the difference is between req.cookies and req.session.cookie. I am using Passport for authentication in Node.js Express.

If I log these two lines in my code:

 console.log('cookies',req.cookies);
 console.log('session',req.session);

I get this output:

cookies { 'mysite.sid.uid.whatever': 's:Ltko5IdDgsAISG0smrKNYaeIVy8nbBzF.MkGmpnf6uUKITIAgN4ws3YXqxJrMaeeSCzlKdjQnqfI' }
session { cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: false },
  views: 8,
  passport: {} }

I am using this configuration:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(busboyBodyParser());
//app.use(busboy());
app.use(cookieParser('cookie parser secret'));
app.use(session({
    secret: process.env["SESSION_SECRET"],
    saveUninitialized: true, // (default: true)
    resave: true, // (default: true)
    store: require('mongoose-session')(mongoose),
    maxAge: 60000,
    key: "mysite.sid.uid.whatever",
    cookie: {secure: false}
}));

I don't really know the difference between using sessions or cookies, except that cookies are client-side only and sessions could be either client or server-side. I have read the documentation from Passport.js a few times, but I still don't really understand what is going on here. Can someone help me out with some explanation? As far as I can tell, it seems best to use server-side session using Redis. But I don't see how you can get away from using client-side data in the end. At some point, you have to rely on the client-side data stored right?

after I login with the express app, the passport object gets populated with a user field, with the MongoDB objectid.

passport: { user: 549290b8246f0e1408e48b13 } }
like image 624
Alexander Mills Avatar asked Apr 27 '26 14:04

Alexander Mills


1 Answers

Typically you will be using cookies when serving browsers. The exception to this being authenticating via an HTTP header or POST parameter token, which are more typical for API requests for example.

It is true you can do client side or server side sessions using cookies, where the entire session data is stored in the cookie in the former (and does not use any storage server-side) or session data is stored server-side (with a session ID stored in a client-side cookie) in the latter.

req.cookies contains cookie values only, no matter if the cookies are session related or not. req.session.cookie contains the Set-Cookie parameters used in the client-side session ID cookie.

like image 199
mscdex Avatar answered Apr 30 '26 07:04

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!