3

I have a create-react-app application in which I enabled the proxy by adding:

"proxy": "http://localhost:3001",

to my package.json. That's working well for API requests to /graphql, but when the web browser request /graphql (for the purpose of loading the UI to run queries) gets handled by the frontend and not proxied. Is it possible to also proxy it?

Same thing happens when I try to do OAuth by visiting https://localhost:3000/auth/facebook, the frontend handles it instead of the backend.

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

1 Answers1

7

It is indeed possible to further customize the proxy.

First, when a web browser requests /graphql or /auth/facebook, it sends an Accept header that holds text/html (among others). The configuration of the CRA proxy specifically ignores requests with this header value:

The development server will only attempt to send requests without text/html in its Accept header to the proxy.

(emphasis in original text)

Luckily, you may override the default configuration and basically hook the proxy middleware to your liking. There are detailed instructions in the docs and even more so in the npm package docs, but the crux of it is:

  app.use(
    '/graphql',
    createProxyMiddleware({
      target: 'http://localhost:3001',
      changeOrigin: true,
    })
  );
MrMister
  • 2,456
  • 21
  • 31
  • 1
    thanks alot. I also had to change `return fetch("/api/graphql", { [...] }` to `return fetch("/graphql", { [...] }` but that probably depends on my backend config – horotab Dec 08 '20 at 06:58