0

I am using Webpack devServer before to intercept requests, then use node-fetch to retrieve html file from remote. How can I preserve Cookies with that approach?

before: function (app, server, compiler) {
    app.get('/*', function (req, res, next) {
        fetch(`https://example.com`)
          .then(res => res.text())
          .then(body => {
            res.send(body)
          });
    });
},
licaomeng
  • 919
  • 2
  • 13
  • 27

1 Answers1

0

Apache Superset has a very nice example of using http-proxy to intercept HTML and applying additional modifications: https://github.com/apache/incubator-superset/blob/c715cad48ea16bb616c9db174e30ea3f5af39fc7/superset-frontend/webpack.proxy-config.js#L137-L153

You don't have to use the fetch API, just reuse proxyResponse in the onProxyRes event.

To preserve response cookies, you'd need to parse the set-cookie headers like this:


/**
 * Parse the `Set-Cookie` header from remote servers.
 */
function parseSetCookie(
  cookieHeaders?: string | number | string[],
): [string[], Cookies] {
  if (!cookieHeaders) return [[], {}];
  const cookieArray = Array.isArray(cookieHeaders)
    ? cookieHeaders
    : [String(cookieHeaders)];
  const cookies: Cookies = {};
  return [
    cookieArray,
    cookieArray
      .map((x) => x.split(';', 1)[0].split('=', 2))
      .reduce((acc, [key, value]) => {
        acc[key] = value;
        return acc;
      }, cookies),
  ];
}

parseSetCookie(res.getHeader('set-cookie'));

Polor Beer
  • 1,814
  • 1
  • 19
  • 18