Using Apollo with multiple Graphql endpoints

If you are using Graphql you may already faced this issue where you have your own Graphql server and also needs to query data from a 3rd party API.

If this API is REST then no problem, you can just use fetch, Axios, etc. But what if this API is using Graphql? How can you tell your Apollo client if a query/mutation belongs to your backend or the other API?

I ran into this issue while developing my first Shopify App. I have Graphql on my backend and Shopify recently migrated to Graphql.

In this post, I will share how I managed to use the same Apollo client to communicate with both.

We can make this happen in 3 simple steps:
1- Create HttpLink to each endpoint

import { ApolloLink } from "apollo-link";

const myLink = new HttpLink({
  uri: '/graphql',
  // other link options...
});

const thirdPartyLink = new HttpLink({
  uri: 'website/graphql',
  // other link options...
});

2- Configure Apollo client

import { ApolloClient } from 'apollo-client';

const client = new ApolloClient({
  link: ApolloLink.split(
    operation => operation.getContext().clientName === "third-party",
    // the string "third-party" can be anything you want,
    // we will use it in a bit
    thirdPartyLink, // <= apollo will send to this if clientName is "third-party"
    myLink // <= otherwise will send to this
  )
  // other options
});

3- finally, when you want to call a query or mutation you just need to pass the clientName to Apollo like this:

useQuery(QUERY, { variables, context: { clientName: 'third-party' } })

// useQuery is a React hook, it may look different for you if you are using something else

That's all! the magic happens inside ApolloLink.split. You give each query/mutation a "context" and Apollo figures out where to send it!

Happy coding ✌️