public
Created

Express: Switch cookie sessions to a header session fore Node Apps built as APIs

  • Download Gist
Readme
1 2 3 4 5
The two files attached are Express Middleware
Srvformat sets the format based on the accept header
to switch it to api mode.
ApiSession uses the req.format set by this to decide
which kinds of sessions to use.
apiSession.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 
module.exports = function apiSession(ex_session){
 
return function apiSession(req, res, next){
if (req.format != 'html') {
var sessionId = req.header('Sessionid');
if (sessionId && sessionId != null) {
//try to load a sessionId
req.sessionStore.get(sessionId, function(err, sess){
if (!err) {
req.sessionStore.createSession(req, sess);
next();
}
else {
req.session.regenerate(function(err){
next();
});
}
});
}
else {
req.session.regenerate(function(err){
next();
});
}
}
else {
next();
}
}
};
srvformat.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 
module.exports = function srvformat(){
 
return function setFormat(req, res, next){
var contentType = req.headers.accept;
if (contentType == '' || contentType == '*/*') {
contentType = 'html';
}
var isBrowser = (contentType.indexOf('html') > -1);
req.params = req.params || {};
if (isBrowser) {
req.params.format = req.format = 'html';
}
else {
req.params.format = req.format = contentType.split('/')[1];
}
next();
}
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.