Skip to content

Instantly share code, notes, and snippets.

@j-mcnally
Created August 18, 2011 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save j-mcnally/1155365 to your computer and use it in GitHub Desktop.
Save j-mcnally/1155365 to your computer and use it in GitHub Desktop.
Express: Switch cookie sessions to a header session fore Node Apps built as APIs
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.
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();
}
}
};
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();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment