Can I add cookies to a webpack dev server proxy?

fnsjdnfksjdb picture fnsjdnfksjdb · Jan 17, 2016 · Viewed 12.1k times · Source

I'm trying to set up a proxy within my webpack dev server. The issue is that I don't control the server I'm connecting to, and I need to authenticate the request.

Is there a way I can add cookies on to the request I send to the proxy server? I've looked through the webpack dev server proxy server page, and the node-http-proxy page it links to, and I don't see any mention of cookies. I'm also not sure if there's a way for me to see these forwarded requests, so I can't tell if anything I'm trying is doing anything.

Any ideas?

Answer

Leon Gibat picture Leon Gibat · Oct 11, 2016

If you need to only rewrite the cookie domain for the proxy, check out the option cookieDomainRewrite in node-http-proxy.

Additionally if you wanted to find a way to inject in custom behavior around cookies on requests / responses, then check out the events you can hook in to:

proxy.on('proxyRes', function (proxyRes, req, res) {
    console.log('RAW Response from the target',JSON.stringify(proxyRes.headers, true, 2));
});


proxy.on('proxyReq', function (proxyRes, req, res) {
    console.log('RAW Request from the target',JSON.stringify(proxyReq.headers, true, 2));
});

https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events

These options can be added to the webpack.config.js for the devServer proxy, like this:

{
    devServer: {
        proxy: {
            onProxyReq: function(proxyReq, req, res){
                proxyReq.setHeader('x-added', 'foobar');
            },
            cookieDomainRewrite: ""
        }
    }
}

https://github.com/chimurai/http-proxy-middleware#http-proxy-events