public
Created

Express Node.js web server that forwards proxied cookies

  • Download Gist
proxycookie.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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
var express = require('express'),
proxy = require('http-proxy'),
app = express.createServer();
 
var routingProxy = new proxy.RoutingProxy();
var apiHost = process.argv[2] ? process.argv[2] : 'my.api.com';
var apiPort = process.argv[3] ? process.argv[3] : '8080';
var apiPrefix = process.argv[4] ? process.argv[4] : '1.1';
 
function onApiProxyEnd(req, res, proxyHeaders) {
if (proxyHeaders &&
proxyHeaders.hasOwnProperty('set-cookie') &&
Object.prototype.toString.apply(proxyHeaders['set-cookie']) === '[object Array]')
{
req.session.cookies = proxyHeaders['set-cookie'];
}
}
 
function apiProxy(pattern, host, port) {
var hasEndListener = false;
 
return function(req, res, next) {
if (req.url.match(pattern)) {
if (req.session && req.session.cookies) {
var cookies = req.session.cookies;
var i = cookies.length;
while (i--) {
if (req.headers.cookie && req.headers.cookie.length > 0) {
req.headers.cookie += ';';
}
req.headers.cookie += cookies[i];
}
}
routingProxy.proxyRequest(req, res, {host: host, port: port});
if (!hasEndListener) {
routingProxy.proxies[host + ':' + port].on('end', onApiProxyEnd);
hasEndListener = true;
}
} else {
next();
}
}
}
 
app.configure(function () {
app.use(express.cookieParser('secret'));
app.use(express.session({secret: 'secret'}))
app.use(apiProxy(new RegExp('\/' + apiPrefix + '\/.*'), apiHost, apiPort));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.static(__dirname));
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
app.use(app.router);
});
 
app.listen(8000);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.