Skip to Main Content

A Front-End Web Development Blog by Kristen Grote.

Headless Craft CMS with GraphQL and React, Part 2: Setting Up Apollo Client

Watch a Video of this Tutorial

While it's certainly possible to use vanilla javascript to query our GraphQL back-end, Apollo Client is an excellent library that makes executing GraphQL queries easy and also caches the retrieved data client-side for better performance. 

Install Apollo Client

In your front-end project, install the following packages (I'm using npm, you can use your package manager of choice):

npm install @apollo/client graphql rxjs

Create a Query Cache

To keep our project structure organized we're going to break our query components into separate files and export/import their contents as needed. Inside a new folder called /data create a file called query-cache.js and paste in this code:

import { InMemoryCache } from '@apollo/client';

const queryCache = new InMemoryCache();

export default queryCache;

This initializes an Apollo cache which Apollo will use to store the data retrieved from our Craft back-end.

Create a Query Client

Inside the /data folder create a new file called query-client.js and paste the following code:

import { ApolloClient, HttpLink } from '@apollo/client';
import queryCache from '@/data/query-cache';

const queryClient = new ApolloClient({
    link: new HttpLink({
        uri: 'https://craft-backend.ddev.site/index.php?action=graphql/api', // <-- the URL of your Craft install
        headers: {
            Authorization: 'Bearer XXXXXX' // <-- the GraphQL token you generated in the Craft control panel
        },
    }),
    cache: queryCache
});

export default queryClient;

This is the main client that we will route our GraphQL requests through. 

Replace the uri with the public URL to your craft installation plus /index.php?action=graphql/api which is Craft's default GraphQL endpoint. 

Replace the Authorization header with the GraphQL token you generated in the Craft control panel in Part 1. Be sure to include the Bearer prefix. 

Also notice we passed in the queryCache we created in the last step.

Add the Apollo Provider to the App Container

Now we need to make our Apollo client available to use throughout the app. Open up your project's top-level app container file (in the Next.js pages router this is located at /src/pages/_app.js). Import the ApolloProvider component and the queryClient object we just created. Then wrap the top-level component in the <ApolloProvider> component like so:

import { ApolloProvider } from '@apollo/client/react';
import queryClient from '@/data/query-client';

export default function App({ Component, pageProps }) {
  return (
    <ApolloProvider client={queryClient}>
      <Component {...pageProps} />
    </ApolloProvider>
  )
}

Now we're ready to send our first query and start populating our front-end with content, which we'll cover in Part 3. 

View the Project Code