Skip to content

Instantly share code, notes, and snippets.

@zivester
Created February 9, 2013 02:31
Show Gist options
  • Select an option

  • Save zivester/4743563 to your computer and use it in GitHub Desktop.

Select an option

Save zivester/4743563 to your computer and use it in GitHub Desktop.
Express (Connect?) does not send cookies on requests where req.session isn't altered. For the case of authentication/login, its useful to have the cookie time extended each time any user interaction exists. Setting a property in req.session should not be required.
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.favicon());
app.use(express.session({
secret : 'secret',
cookie : {
httpOnly : false,
maxAge : 10000
}
}));
function authenticate(req){
req.session.user = "JOHN";
req.session.views = 1;
}
function sendInfo(req, res){
var sess = req.session;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + sess.views + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.end();
}
// This route sends the cookie every time, because req.session is being modified
app.get('/good', function(req, res){
var sess = req.session;
if (sess.user) {
// Alters req.session so the cookie gets resent!
sess.views++;
sendInfo(req, res);
res.end();
} else {
authenticate(req);
res.end('refresh... this session will last 10 seconds after your last refresh');
}
});
// This route does not send the cookie every time, because req.session is only modified initially
// For the simplest case, a user will be de-authenticated after the initial maxAge is reached
app.get('/bad', function(req, res, next){
var sess = req.session;
if (sess.user) {
// This does not set anything in req.session, so the cookie never gets sent!
// Cookie will expire 10 seconds from first load, ignoring refreshes
sendInfo(req, res);
res.write('<p>^^^^ Lies ^^^^</p>');
res.end();
} else {
authenticate(req);
res.end('refresh... this session will only last 10 seconds');
}
});
app.get('*', function(req, res){
res.redirect('/bad');
});
// Run server
server.listen(3000, "", function(){
var address = server.address();
console.log("running on http://%s:%s", address.address, address.port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment