Handling multiple GraphQL server endpoints in a single React Apollo app

This is often not the case, let’s say in 95% of the time your frontend app will have only one GraphQL endpoint that resolves data. But I have recently come across a project where our frontend app needed to talk to two different GraphQL servers. So we came up with a solution that worked in our case.

This is actually fairly simple, what we need to do is to create an abstraction around ApolloProvider with our own provider, and control the actual client that is being used inside of that context.

Let’s create a file ApolloContext.tsx

What this allows you to do, is to change the client whenever it is needed in your app. For example, in this next component, we will switch to an external endpoint, use it inside of this component, and of course, clean up on component unmount.

Like I’ve said in the beginning if you get to the case that you need two endpoints you need to rethink your project structure, this is just a quick solution to go around that hurdle if you come to it.

Highly motivated, dedicated developer. I’m also a functional programming enthusiast and that is something that I’m exploring in the last couple of years.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store