eeandrew
eeandrew

Reputation: 89

Session data is not saving to memory while using express-session

I am encountering a problem when I try the following example using different express-session versions.

Using express-session 1.0.2:

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

var app = connect();
app.use(cookieParser())
.use(session({secret:'sessionsecret',cookie:{maxAge:60000}}))
.use(function(req,res,next){
    if(req.session.views){
        res.setHeader('Content-Type','text/html');
        res.write('<p>views ' + req.session.views + '</p>');
        //Here
        res.end();
        req.session.views++;
    }
    else {
        req.session.views = 1;
        res.end('welcome to the demoe. Try refresh this page');
    }

})
.listen(3000);

This works; the view counter keeps increasing when I refresh the page. However, when I change express-session to 1.8.2 (the latest), that code ceases to work and the view counter stays at 1. But after I modify the code into following, it works again:

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

var app = connect();
app.use(cookieParser())
.use(session({secret:'sessionsecret',cookie:{maxAge:60000}}))
.use(function(req,res,next){
    if(req.session.views){
        res.setHeader('Content-Type','text/html');
        res.write('<p>views ' + req.session.views + '</p>');
        //Here
        req.session.views++;
        res.end();
    }
    else {
        req.session.views = 1;
        res.end('welcome to the demoe. Try refresh this page');
    }

})
.listen(3000);

It seems the session data is saving before the response is sent in the new express-session. Can someone explain this?

Upvotes: 0

Views: 494

Answers (1)

Brendan
Brendan

Reputation: 2935

Yes, ExpressJS sessions cannot save the req.session object after res.end() is called - or any content data is sent.

The reason it does this is because cookies can only be set (therefor the session can only be saved) when the headers are being sent; after the headers are sent (and content is sent), the cookie cannot be reset and the session cannot be saved.

You can see the code in action here.

Upvotes: 1

Related Questions