0

I'm having a webpack-dev-server enabled with watcher and reload on every change.

This frontend dev server is in docker container, and is proxying everything to another docker container, backend, which is using server-side-rendering.

So, frontend has exposed port 8080 to host machine. When you visit localhost:8080, it proxies everything to nginx:8000, which then servers php files (including the HTML code of this server).

devServer: {
   port: 8080,
   host: '0.0.0.0', // to accept connections from outside container
   disableHostCheck: true,

   watchOptions: {
      poll: 1000
   },
   writeToDisk: true,

 
   proxy: {
      "**": {
         target: "http://nginx:80", // Proxy to backend
         changeOrigin: true,
         secure: false,
         logLevel: "debug",
      }
   }
}

That works fine, unless the server sends redirect. In that case, the proxied response has location nginx:8000<redirected_url>.

How to handle such case?

According to documentation, webpack dev server uses a http-proxy-middleware.

I tried it's options autoRewrite:true and hostRewrite:true but it didn't work.

2 Answers 2

0

What helped me is custom interceptor in onProxyRes, which handles the redirects.

Rewrites the location, which browser should be redirected to with current dev server url + the rest of the URL where proxied server redirect pointed to.

   proxy: {
                "**": {
                    target: "http://nginx:80", // Proxy to backend
                    changeOrigin: true,
                    secure: false,

                    // This handles the redirects
                    onProxyRes: function (proxyRes, req, res) {
                        if ([301, 302, 307, 308].indexOf(proxyRes.statusCode) > -1 && proxyRes.headers.location) {
                            const originalUrl = new URL(req.originalUrl, req.protocol + '://' + req.headers.host);
                            const redirectLocation = new URL(proxyRes.headers['location']);

                            // Rewrite the location to devServer origin and the path + query string + hash from response
                            proxyRes.headers['location'] = originalUrl.origin + redirectLocation.pathname + redirectLocation.search + redirectLocation.hash;
                        }
                    }
                },
            }
Sign up to request clarification or add additional context in comments.

Comments

0

Another option is to use changeOrigin: false. This will not rewrite the origin on all request - if your server is creating some URLs in responses from $request->url(), rewriting origin will modify all links - what you probably don't want to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.