Gatsby proxy to multiple backends with same prefix

Viewed 556

I have two different API backends running on ports 8080 and 9090. I am developing frontend with gatsby.
Is it possible to proxy /api/specific-path to one backend (example to 9090) and all other /api calls to the other backend (8080)?

Tried this in gatsby-config.js, but all /api requests are going to 8080:

  proxy: [
    {
      prefix: "/api",
      url: "http://localhost:8080",
    },
    {
      prefix: "/api/specific-path",
      url: "http://localhost:9090",
    },
  ],

Perhaps using nginx as reverse proxy for backends, and sorting requests there would solve the problem, but ideally I would like to avoid setting up extra services for local development.

1 Answers

If you're looking to do this during development only then yes, you can use express middleware to set up multiple path-based proxies. In production, Gatsby does not run server-side and cannot configure response headers or proxy settings.

In gatsby-config.js:

const proxy = require("http-proxy-middleware")

module.exports = {
  plugins: [],

  developMiddleware: app => {
    app.use(
      "/api/specific-path",
      proxy({
        target: "http://localhost:9090",
        pathRewrite: {
          "/api/specific-path": "", // optionally remove the path prefix from the proxied request
        },
      })
    )

    app.use(
      "/api/",
      proxy({
        target: "http://localhost:8080",
        pathRewrite: {
          "/api/": "",
        },
      })
    )
  },
}

Note that http-proxy-middleware is included as part of Gatsby (webpack-dev-server, really) so you don't have to to add it to your dev dependencies unless you care about the version you're using for some reason.

Related