Proxied http response fails to set cookie

3.4k views Asked by At

I'm developing a web application and testing it using Google Chrome 60.0.3112.113.

To simplify the development process I use a node.js development web server with http-proxy-middleware to proxy my API request to the backend.

Now when I send a HTTP POST request using axios to one of the API endpoints to create a session in my backend, I get back slightly altered responses headers (copied from DevTools):

Direct response
HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json
Set-Cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
Proxied response
HTTP/1.1 200 OK
X-Powered-By: Express
connection: close
content-length: 122
content-type: application/json
set-cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
Date: Thu, 07 Sep 2017 11:06:43 GMT

The problem is that chrome doesn't set the cookie specified in the proxied response (DevTools->Application->Storage->Cookies stays empty), however the direct response sets the cookie as expected.

Cookies are shown correctly in DevTools->Network->My Request->Cookies. Both versions (direct and proxied) are being accessed via http://localhost:[8080 / 3000]

Could the lowercase set-cookie header be ignored in chrome? Or could the other headers interfere with setting of the cookie?

Btw: Works fine in Safari 10.1.2 (12603.3.8)

2

There are 2 answers

0
Alen Vlahovljak On

Set cookieDomainRewrite: 'localhost'

1
Dr. Zhu On
// proxy middleware options 
var options = {
    target: 'http://localhost:8081', // target host 
    changeOrigin: true,               // needed for virtual hosted sites 
    ws: true,                         // proxy websockets 
    logLevel: "debug",
    pathRewrite: {
        '^/src/api/' : '/api/'
    },
    onProxyRes: function (proxyRes, req, res) {
        if (proxyRes.headers['set-cookie'] != undefined) {
            req.session['cookie'] = proxyRes.headers['set-cookie'];  // must be or you will get new session for each call
            req.session['proxy-cookie'] = proxyRes.headers['set-cookie'];  // add to other key because cookie will be lost
        }
        console.log("response: " + req.session.id);
        console.log(req.session);
    },
    onProxyReq: function (proxyReq, req, res) {
        // check for whether the session be freshed
        if (req.session.view)
            req.session.view ++;
        else
            req.session.view = 1;

        // use ower key to restore cookie
        if (req.session['proxy-cookie'] != undefined)
            proxyReq.setHeader('cookie', req.session['proxy-cookie'][0]);

        console.log("request: " + req.session.id);
        console.log(req.session);
    }
};