What's the difference between express-session and cookie-session?
Asked Answered
N

9

76

I am new with Express. As Express 4.x has removed bundled middlewares.

Any middleware I want to use should be required. When I read the README with express-session and cookie-session on github, I find it hard to understand the difference.

I tried to write some simple code to figure it out. I ran it twice for each middleware.

var express = require('express')
  , cookieParser = require('cookie-parser')
  , session = require('cookie-session')
  , express_sess = require('express-session')
  , app = express();

app.use(cookieParser())
app.use(session({ keys: ['abc'], name: 'user' }));
//app.use(express_sess({ secret: 'abc', key: 'user'}));
app.get('/', function (req, res, next) {
    res.end(JSON.stringify(req.cookies));
    console.log(req.session)
    console.log(req.cookies)
});

app.listen(3000);

For cookie-session, I always get {} in my terminal.

For express-session, I get things like this.

req.session: { cookie: { 
     path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true 
   } 
}

req.cookie: {user: 's:aJ97vKA5CCwxqdTj0AV1siRQ.fWusS5+qfCKICtwkfrzcZ/Gq8P0Qdx/kx8mTBhoOhGU'}

It really confuses me. So how to explain the result with the basic use? And what's the difference between them? When should I use them?

Nineteen answered 9/5, 2014 at 13:59 Comment(1)
S
56

Basically, express-session is more abstract, it supports different session stores (like files, DB, cache and whatnot).

And cookie-session is a simple / lightweight cookie-based (cookie is the only storage engine supported: all the session info is stored on the client, in a cookie) session implementation. This kind of sessions is probably most famous for its Rails implementation.

Solent answered 9/5, 2014 at 14:18 Comment(2)
is there a good place where I can read about the advantages/disadvantages of client-only vs server-side cookies/sessions? for someone who knows nothing, it's hard to know where to start on thisMilliary
@AlexMills The link to the Rails guide in the answer pretty much explains it.Solent
B
25

The basic difference between both these relates to how and where is the session data being stored. Cookie session is basically used for lightweight session applications where the session data is stored in a cookie but within the client [browser], whereas, Express Session stores just a mere session identifier within a cookie in the client end, whilst storing the session data entirely on the server. Cookie Session is helpful in applications where no database is used in the back-end. However, the session data cannot exceed the cookie size. On conditions where a database is used, it acts like a cache to stop frequent database lookups which is expensive.

Buote answered 13/11, 2017 at 8:56 Comment(0)
W
10

express-session stores the session identifier in the cookie while the actual session data resides in backend session store like connect-redis, where as cookie-session allows you to store the session data in a cookie (client-side).

From the documentation of cookie-session:

A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like 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.

The main advantage of using cookie-session is when you have a clustered node.js app, then you don't have to rely on sharing session data between forked processes.

Whiskey answered 18/4, 2018 at 1:2 Comment(1)
That is true about the clustering part and its big plus so what about security side of thingsSuperdreadnought
B
8

Let me share an important difference I found: secure cookies.

I have a node process behind an nginx proxy which handles SSL.

I tried with express-session, but I could not enable secure cookies, see issue here.

Then I tried with almost the same code, but with cookie-session instead, something like

   const expressSession = require('cookie-session')

   var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days

    const session = expressSession({
      secret: sessionSecret,
      resave: false,
      saveUninitialized: true,
      cookie: {
        secureProxy: true,
        httpOnly: true,
        domain: 'example.com',
        expires: expiryDate
      }
    })

    app.use(session)

I just changed require('express-session') to require('cookie-session') and added secureProxy: true,: everything worked out of the box.

Note also that both packages are maintained by expressjs so probably in my use case I was lucky finding out that cookie-session fits my needs.

Benenson answered 2/3, 2016 at 15:38 Comment(2)
Note that this was caused by a misconfigured reverse proxy in front of express (X-Forwarded-Proto was missing). Secure cookies are fully supported by express-session as well.Liggitt
I'm not sure that this post is right - most of the configuration below 'const session=....' is specific to express-session and incompatible with cookie-session. Coding as above just throws error messages.Karilla
S
8

The official Express.js documentation refers to

The main difference between these two modules is how they save cookie session data.

The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store; see the list of compatible session stores.

In contrast, cookie-session middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don’t exceed the limit, don’t exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then express-session may be a better choice.

Schaffer answered 29/1, 2020 at 12:0 Comment(0)
D
2

The get a non-empty console.log(req.session) you need to set session values before logging.

From the cookie-session repo (https://github.com/expressjs/cookie-session):

app.get('/', function (req, res, next) {
 req.session.views = (req.session.views || 0) + 1
 console.log(req.session)
 res.end(req.session.views + ' views')
})

If you never set any info on the req.session object, it will return empty.

Deathbed answered 7/6, 2018 at 23:31 Comment(0)
S
2

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.
  • cookie-session stores the session data on the client within a cookie
Shofar answered 31/8, 2021 at 13:15 Comment(2)
Can't session data stored on the client be changed by the user?Cadelle
@Cadelle cookies are cryptographically signed by cookie-session which prevents tampering with the contents of the cookie.Osseous
N
1

v4-> cookie-session is (Establish cookie-based sessions.) equals in ->v3 express.cookieSession

v4-> express-session is (Establish server-based sessions (development only)). equals in ->v3 express.session

Nauplius answered 27/8, 2019 at 14:11 Comment(0)
S
0

express-session stores session data into configurable backends, ranging from memory to any number of databases, thus allowing essentially unlimited session storage.

cookie-session stores session data into cookies, thus being limited to a bit under 4k bytes of session storage.

Most of the rest of the differences are consequences of this decision:

cookie-session works without depending on an external datastore (so less infrastructure to set up, configure, maintain).
cookie-session works behind load balancers without 'sticky-sessions' having to be enabled/configured.

Snuck answered 7/8, 2022 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.