javascriptgraphqlnext.jsapolloapollo-client

Using multiple endpoints in Apollo Client


I have learned Apollo + GraphQL through Odyssey. Currently, I am building my own project using Next.js which required fetching data from 2 GraphQL endpoints.

My problem: How can I fetch data from multiple GraphQL endpoints with ApolloClient?

Below is my code for my first endpoint:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const client = new ApolloClient({
  ssrMode: true,
  link: createHttpLink({
    uri: "https://api.hashnode.com/",
    credentials: "same-origin",
    headers: {
      Authorization: process.env.HASHNODE_AUTH,
    },
  }),
  cache: new InMemoryCache(),
});

export default client;

Solution

  • What you are trying to accomplish is kinda against Apollo's "One Graph" approach. Take a look at gateways and federation - https://www.apollographql.com/docs/federation/

    With that being said, some hacky solution is possible but you will need to maintain a more complex structure and specify the endpoint in every query, which undermines the built-in mechanism and might cause optimization issues.

    //Declare your endpoints
    const endpoint1 = new HttpLink({
        uri: 'https://api.hashnode.com/graphql',
        ...
    })
    const endpoint2 = new HttpLink({
        uri: 'endpoint2/graphql',
        ...
    })
    
    //pass them to apollo-client config
    const client = new ApolloClient({
        link: ApolloLink.split(
            operation => operation.getContext().clientName === 'endpoint2',
            endpoint2, //if above 
            endpoint1
        )
        ...
    })
    
    //pass client name in query/mutation
    useQuery(QUERY, {variables, context: {clientName: 'endpoint2'}})
    

    This package seems to do what you want: https://github.com/habx/apollo-multi-endpoint-link

    Also, check the discussion here: https://github.com/apollographql/apollo-client/issues/84