skip to Main Content

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


  1. Chosen as BEST ANSWER

    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;
                            }
                        }
                    },
                }
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search