DEV Community

Cover image for Using Apollo with multiple Graphql endpoints
Jamal Mashal
Jamal Mashal

Posted on • Updated on • Originally published at jamalx31.com

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 ✌️

Oldest comments (4)

Collapse
 
itsjzt profile image
Saurabh Sharma

Oh this is a nice approach.

We also make shopify apps at codeword, but we call shopify queries in backend and map those to our graphql api, it works nice for us since we also want some control in few queries

Collapse
 
jamalx31 profile image
Jamal Mashal • Edited

yes, In Shopify use case our app actually sends the query to our backend and then use proxy to send it to Shopify (you can't send the query directly from the client since you need API credentials you can't expose).
But using this method makes it easier to tell the server which query should go where

Collapse
 
mravangi profile image
Mostafa Ravangi

thanks a lot

Collapse
 
saherelgendy profile image
saher-elgendy

thank you, this is helpful