Prompt

How do I use GraphQL with a headless CMS for a Next.js frontend?

Technology / Developer Tools2 observationsLast seen Nov 9, 2026

Latest observation

Nov 9, 2026OpenAI APIWeb search: off

Using GraphQL with a headless CMS in a Next.js frontend usually looks like this:

  1. Your CMS stores content
  2. GraphQL exposes that content via an API
  3. Your Next.js app queries the API
  4. You render the returned data in pages/components

Typical setup

Common headless CMS options with GraphQL support include:

  • Contentful
  • Sanity
  • Strapi
  • Hygraph
  • Prismic (often via APIs/wrappers depending on setup)

Basic flow

1) Get your GraphQL endpoint and auth token

From your CMS, you’ll usually get:

  • a GraphQL endpoint URL
  • an API token / bearer token
  • maybe a space/project ID

Example:

https://your-cms.com/graphql

2) Query the CMS from Next.js

You can use fetch, Apollo Client, urql, or GraphQL-request. For simple cases, fetch is enough.

Example with fetch

// lib/graphql.js
export async function fetchGraphQL(query, variables = {}) {
  const res = await fetch(process.env.CMS_GRAPHQL_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.CMS_TOKEN}`,
    },
    body: JSON.stringify({ query, variables }),
  });

  const json = await res.json();

  if (json.errors) {
    throw new Error(JSON.stringify(json.errors));
  }

  return json.data;
}

3) Use it in a page or server component

App Router example

// app/page.js
import { fetchGraphQL } from '@/lib/graphql';

const query = `
  query {
    posts {
      title
      slug
      excerpt
    }
  }
`;

export default async function HomePage() {
  const data = await fetchGraphQL(query);

  return (
    <main>
      <h1>Blog</h1>
      <ul>
        {data.posts.map((post) => (
          <li key={post.slug}>
            <a href={`/posts/${post.slug}`}>{post.title}</a>
            <p>{post.excerpt}</p>
          </li>
        ))}
      </ul>
    </main>
  );
}

If you use dynamic routes

// app/posts/[slug]/page.js
import { fetchGraphQL } from '@/lib/graphql';

const query = `
  query PostBySlug($slug: String!) {
    post(where: { slug: $slug }) {
      title
      content
    }
  }
`;

export default async function PostPage({ params }) {
  const data = await fetchGraphQL(query, { slug: params.slug });

  return (
    <article>
      <h1>{data.post.title}</h1>
      <div>{data.post.content}</div>
    </article>
  );
}

Recommended patterns

Use server-side fetching when possible

With Next.js, prefer fetching content on the server:

  • better SEO
  • keeps tokens secret
  • avoids exposing CMS credentials in the browser

Use caching/revalidation

If content changes occasionally, use:

  • static generation
  • ISR / revalidation
  • fetch cache options

Example:

fetch(url, { next: { revalidate: 60 } })

Use GraphQL Code Generator

This helps:

  • generate types
  • catch query mistakes early
  • improve autocomplete

Keep GraphQL queries near the components

This makes it easier to see what data each page needs.

If you want client-side fetching

If a component needs live updates or user-triggered data loading, use Apollo or urql in a client component.

Best practices

  • Don’t expose secret tokens in client code
  • Query only the fields you need
  • Use fragments for reusable query parts
  • Handle loading and error states
  • Consider pagination for large collections

Example with Apollo Client

If you prefer Apollo:

npm install @apollo/client graphql

Then create a client and use ApolloProvider in your app.


If you want, I can give you:

  1. a full Next.js App Router example
  2. a Strapi/Contentful/Sanity-specific setup
  3. a GraphQL Code Generator setup with TypeScript

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.