Search code examples
node.jssessionexpressexpress-session

Differentiate express-session sessions in chrome tabs


I am trying to assign to each user a "req.session.pseudo", but when I try to connect in different tabs, it display me the same session.

Here is an exemple with a "req.session.page_views".

Here is the code :

var express = require('express');
var session = require('express-session');
var app = express();

app.use(session({
secret: 'ssshhhhh',
resave: false,
saveUninitialized: true
}));

app.get('/', function(req, res) {
if(req.session.page_views){
    req.session.page_views++;
    res.send("You visited this page " + req.session.page_views + " times");
} else {
    req.session.page_views = 1;
    res.send("Welcome to this page for the first time!");
}
});

the result on my first tab:

Welcome to this page for the first time!

the result on my second tab:

You visited this page 2 times

I hope to have been clear about my problem. Thank you.


Solution

  • Tabs share cookies, and cookies are used to identify sessions. If tab #1 gets a session cookie, tab #2 will send that same session cookie to the server, so both tabs share the same session.

    You can create one session in your browser's "regular" mode, and one session in its "private" (incognito) mode, but that's about it (tabs created in each mode also share the same cookie for that mode, at least in Chrome, so you can't create multiple incognito windows/tabs and create a new session in each).

    Possibly, there are extensions for your favorite browser that may be used to create multiple sessions concurrently, but you'd have to search for those.