Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure a webpack proxy for multiple URLs efficiently?

I'm using webpack dev server to build a single page application. There are many routes like /api, /alpha, /bravo ... /zulu, and they all need to be proxied.

I wrote webpack.config.js file to proxy all URLs.

proxy: {
  "/api": "http://localhost:3000",
  "/alpha": {
    target: "http://localhost:8080",
    pathRewrite: { "^/alpha": "" }
  },
  "/bravo": {
    target: "http://localhost:8080",
    pathRewrite: { "^/bravo": "" }
  },
  "/charlie": {
    target: "http://localhost:8080",
    pathRewrite: { "^/charlie": "" }
  },
  ...
  "/zulu": {
    target: "http://localhost:8080",
    pathRewrite: { "^/zulu": "" }
  },
}

It works well, but I had to write too many codes. I wonder is there any way to reduce it? I thought webpack supports a regular expression for this problem, but I couldn't get a solution from the official docs :(

like image 839
Simon Park Avatar asked Oct 22 '25 16:10

Simon Park


1 Answers

Webpack dev server's proxy settings are a spin off of the https://github.com/chimurai/http-proxy-middleware#http-proxy-middleware-options.

Documentation says you can use a function on the rewrite prop to do some complex regex work. This, coupled with the ability to define multiple proxy entries and context entries, I would suggest something along the lines of:

proxy: [{
  "/api": "http://localhost:3000",
},{
  context: ['/alpha', '/bravo', '/charlie', '/zulu'],
  target: 'http://localhost:8080',
  rewrite: function (path, req) { return path.replace(/\/(.*?)/g, '') }
}]

This reduces your growing list down to a single array.

Hope this helps!

like image 86
Devin Olsen Avatar answered Oct 25 '25 11:10

Devin Olsen