Mon May 30 2022

How to add multiple GraphQL endpoints to Apollo

Learn how to work with more than 1 GraphQL endpoints when you are working with Apollo

Problem

I was working on a project recently where I needed to query two GraphQL endpoints. This was as there was a CMS I needed to fetch some data from (endpoint 1) and my own backend (endpoint 2) which was what controlled authentication.

I couldn't find much info on how to go about this officially, but after reading some documentation and code of some other devs who attempted the same, here is what I did.

1import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
2import { RetryLink } from "@apollo/client/link/retry";
3const TOKEN = process.env.CONTENTFUL_ACCESS_TOKEN;
4const SPACE = process.env.CONTENTFUL_SPACE_ID;
5const URL = `https://graphql.contentful.com/content/v1/spaces/${SPACE}`;
6// take a closer look at whats happening below. I have two 2 HttpLinks.
7// The first will run when I make queries or mutations with 'mongoDB'
8// all queries without 'mongoDB' will be diverted to the contentful endpoint
9const directionalLink = new RetryLink().split(
10 (operation) => operation.getContext().clientName === "mongoDB",
11 new HttpLink({ uri: `/api/profile` }),
12 new HttpLink({
13 uri: URL,
14 headers: {
15 Authorization: `Bearer ${TOKEN}`,
16 },
17 })
18);
19// this is just the creation of the client, nothing too special.
20// If you want to see a full example of how apollo clients are used,
21// check these examples out - https://nextjs.org/examples
22function createApolloClient() {
23 return new ApolloClient({
24 ssrMode: typeof window === "undefined",
25 link: directionalLink,
26 cache: new InMemoryCache(),
27 });
28}

Usage

Here is how we would tell Apollo which endpoint it needs to use when making queries or mutations

1const [loadUserData] = useLazyQuery(USER_DATA,
2 {
3 context: { clientName: "mongoDB" },
4 variables: { email: session?.user?.email || "" },
5 onCompleted: (data) => {
6 //do something with data
7 },
8 });

This wasn't a very long blog post as the goal was to share how to go about using 2 endpoints in GraphQL. I haven't tried this with more than 2 but if you have and had any issues with it, let me know and I can give it a go!

Know of a better way to go about this? Also let me know!

Comments