How to connect NextJS to Keystone

Keystone is a truly open-source headless CMS with no limitations and incredible flexibility. Here's how to connect it to a NextJS site with the handy GraphQL schema it creates from your content model.

Sep 1, 2023

Getting the Frontend and Backend talking to each other:

Video: https://www.apollographql.com/blog/apollo-client/next-js/next-js-getting-started/

We will use the Apollo Client to fetch data from the Keystone GraphQL API. First, ensure you have the required dependencies installed by running this command:

npm install @apollo/client@alpha @apollo/experimental-nextjs-app-support graphql

Now, create a /lib/client.js file and add the following code:

javascriptCopy code// lib/client.js
import { HttpLink } from "@apollo/client";
import {
  NextSSRInMemoryCache,
  NextSSRApolloClient,
} from "@apollo/experimental-nextjs-app-support/ssr";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc";

export const { getClient } = registerApolloClient(() => {
  return new NextSSRApolloClient({
    cache: new NextSSRInMemoryCache(),
    link: new HttpLink({
      uri: "[your API endpoint]", // Replace with your Keystone GraphQL API endpoint
    }),
  });
});

Fetch Content from Keystone CMS

Now that our Apollo Client is set up, let's retrieve content from a Keystone CMS collection. Here's an example of fetching posts:

javascriptCopy code// app/page.js
import { getClient } from "../../lib/client"
import { gql } from "@apollo/client";

const query = gql`
  query Posts {
    posts {
      title
      intro
      publishedDate
      status
    }
  }
`;

export default async function Page() {
  const { data } = await getClient().query({ query });

  return (
    <main>
      Posts from Keystone
      <ul>
        {data.posts.map((post) => (
          <li key={post.title}>
            <h2>{post.title}</h2>
            <p>{post.intro}</p>
            <p>{post.publishedDate}</p>
            <p>{post.status}</p>
          </li>
        ))}
      </ul>
    </main>
  );
}

In this example, we define a GraphQL query to fetch posts from Keystone CMS then we use Apollo Client to execute the query and display the results on our Next.js page.

Resources:

For more KeystoneNextJS tutorials, check out these level-up courses.

https://levelup.video/tutorials/keystone-js/overview-graphql-apollo

https://www.apollographql.com/blog/apollo-client/next-js/next-js-getting-started/

More about the tools: