What's difference with express-session and cookie-session?

40,888

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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.

Solution 5

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.

Share:
40,888
Tinple
Author by

Tinple

:D

Updated on September 01, 2021

Comments

  • Tinple
    Tinple over 2 years

    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 feel it hard to understand the difference.

    So I try to write simple code to figure it out. I run 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?

  • Alexander Mills
    Alexander Mills over 9 years
    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 this
  • bredikhin
    bredikhin over 9 years
    @AlexMills The link to the Rails guide in the answer pretty much explains it.
  • Max Truxa
    Max Truxa about 8 years
    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.
  • codefreaK
    codefreaK over 5 years
    That is true about the clustering part and its big plus so what about security side of things