Search code examples
webpackproxywebpack-dev-serverhttp-proxy-middleware

How do I proxy _some_ requests to '/' using http-proxy-middleware for Webpack?


I'm trying to solve a unique problem w/ an app where I need to use webpack dev-server's proxy functionality to proxy specific requests through to a backend service.

The problem I'm having is figuring out how to handle an odd use case.

I have Webpack DevServer (WDS) serving up my index.html for a Single Page App w/ multiple client-side routes. The SPA makes clientside AJAX/fetch requests to different endpoints that need to be proxied. Unfortunately, one of the endpoints is / on the server but only for requests w/ a specific Content-Type header (I can't change the path this service is listening on, so adding some kind of path-prefix is not an option here).

I've tried using the bypass option in my WDS config to do something like this:

proxy: {
        "/": {
          target: "http://ows.local:6273",
          logLevel: "debug",
          secure: false,
          bypass: (req) => {
            console.log(`req.path => `, req.path)
            if (req.headers.accept.indexOf('html') !== -1) {
              console.log('Skipping proxy for HTML request.')
              return 'src/index.html'
            }
            return null
          }
        }
      }

The problem arises w/ initial calls for HTML, that which WDS should be serving up w/ the compiled .js and .css bundles injected. All I get is the base src/index.html w/o the injected assets (no injected <script> tags). This makes sense because I know I'm telling the proxy here, "Don't proxy this request to the target, just serve up the contents of this file", but that's not what I want. I need the compiled index.html that WDS serves as default, w/ the injected assets.

So here's my question w/ some specificity:

How can I essentially tell the proxy, "For requests that have Content-type: application/json(or whatever), go ahead and proxy them through to the target, but for calls for HTML, don't proxy then, just serve up the WDS-compiled index.html"?


Solution

  • Turns out, all it took to solve this was to adjust the return value of the bypass() function.

    proxy: {
            "/": {
              target: proxyTargetUtl,
              secure: false,
              logLevel: "debug",
              bypass: (req) => (req.headers.accept.includes("html") ? "/" : null)
            }