Search code examples
javascriptwebpackwebpack-dev-server

How to rewrite the request path to point to another path under the same domain with webpack-dev-server?


What I want to achieve is to change the request URLs in the format of /**/locales/**/*.json, e. g. changing from some.domain.com/subpath/locales/another/file.json to some.domain.com/locales/file.json using webpack-dev-server. My configuration was working fine some days ago but now I got a EHOSTUNREACH error, after moving my code and finally reverting back to the original working implementation now I get a ETIMEDOUT error.

<e> [webpack-dev-server] [HPM] Error occurred while proxying request some.domain.com/locales/file.json to https://some.domain.com/ [ETIMEDOUT] (https://nodejs.org/api/errors.html#errors_common_system_errors)

I'm using my hosts file to resolve the some.domain.com. My actual configuration is:

const HOST_DOMAIN = 'some.domain.com'

return {
  devServer: {
    server: { type: "https" },
    port: 443,
    compress: true,
    allowedHosts: "all",
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    client: {
      webSocketURL: `auto://${HOST_DOMAIN}/ws`,
    },
    proxy: {
      '/**/locales/**/*.json': {
        target: 'https://' + HOST_DOMAIN,
        pathRewrite: function (path) {
          const parts = path.split('/');
          return '/locales/' + parts.pop();
        },
        secure: false
      }
    },
    static: [
      {
        directory: path.join(__dirname, "src/locales"),
        publicPath: `/locales`,
      },
    ],
  },
  // ...
}

I have tried to set the originRewrite to true as well, but it didn´t work.

Is it possible to achieve this? If so, is this the righ way? I don't know why it stopped working.


Solution

  • Although the proxy option can be used to achieve the URL rewriting in my use case, I found it's not its mainly purpose and can bring limitations and add more complexity to the original problem.

    Therefore, the historyApiFallback option is more suitable for rewriting URLs and serving static files as noted in the documentation.

    Then, the webpack configuration result in something like this:

    const path = require("path");
    
    // ...
    devServer: {
      historyApiFallback: {
        rewrites: [
          {
            from: /^\/([^/]+)\/locales\/(.+\.json)$/,
            to: context => `/locales/${path.basename(context.parsedUrl.pathname)}`
          },
        ],
      },
      // ...
    }
    

    The above will intercept all requests in the format of /**/locales/**/*.json and use the to property to rewrite the URL, which in my case is using a function that reads the URL from the context object and extracts the filename to create the correct path where the static files are served from.