How to setup a webpack dev server using both historyApiFallback and proxying remote api requests?

Viewed 7294

I have a react application which uses react-router, so it's making use of HTML5 history API, I've tried historyApiFallback set to true to serve 404 paths serving the same index.html instead of returning the HTTP response.

That single page application does some requests to a remote API server, that's why I also need to proxy some requests to the express server I'm also running while developing. Web react application is served on port 3000 and API runs on port 3001.

So I've tried:

devServer:{
    contentBase: 'src/www',  //Relative directory for base of server
    devtool: 'eval',
    hot: true,        //Live-reload
    inline: true,
    port: 3000,        //Port Number
    host: 'localhost', //Change to '0.0.0.0' for external facing server
    historyApiFallback: true,
    proxy: {
      '^\/users|sitters|bookings': {
        target: 'http://127.0.0.1:3001',
        rewrite: function(req) {
          req.url = req.url.replace(/^\/api/, '');
        }
      }
    }
  },
  devtool: 'eval',
  output: {
    path: buildPath,    //Path of output file
    filename: 'app.js'
  },

So I what I want is hitting the remote api server if the request's path starts with either /users or /sitters or /bookings but go for historyApiFallback (serve index.html) otherwise.

Of course right now historyApiFallback works always serving the HTML file but I'd also need the proxy to be working.

3 Answers

I'm using webpack v4 and adding proper value for pathRewrite inside proxy worked for me.

For example, you are hosting client on localhost:8080 and API on localhost:3000. Then your webpack devServer section will go like below.

devServer: {
    historyApiFallback: true,
    proxy: {
        '/graphql': {
            changeOrigin: true,
            pathRewrite: { '^/api': '' },
            target: 'http://localhost:3000/api'
        }
    }
}
Related