Skip to Content
FrameworksNext.js

Next.js

With the App Router, fetch CMS data directly in Server Components: await query.get(). No data fetching library or extra package is needed. Next’s own fetch features work through fetchOptions, and because every query has a deterministic URL, Next’s request memoization and data cache key on it automatically.

Client setup

headquery init writes this client to src/cms.ts for Next.js projects:

// src/cms.ts (written by headquery init) import { } from "@headquery/statamic"; import type { Schema } from "./cms.generated"; export const = <Schema>({ : .. ?? "https://cms.example.com", });

It reads a NEXT_PUBLIC_ variable, so the same client works in Server and Client Components. That is enough while your API is public and read-only.

As soon as you add a token, an internal CMS URL or next fetch options, make the client server-only:

// src/cms.ts import "server-only"; import { } from "@headquery/statamic"; import type { Schema } from "./cms.generated"; export const = <Schema>({ : ..!, // Next's data cache: revalidate CMS responses every 60 seconds : { : { : 60 } }, });

server-only makes the build fail if this module is ever imported from a Client Component. On the server the import does nothing. That matters for three reasons:

  • Secrets stay on the server. A token or an internal CMS URL would otherwise end up in the browser bundle after a single "use client" import.
  • A build error instead of a confusing runtime error. Next replaces env variables without the NEXT_PUBLIC_ prefix with undefined in client bundles, so HEADQUERY_BASE_URL would be missing in the browser.
  • Server-only settings don’t leak. next: { revalidate } only has an effect on the server.

For data fetched in the browser, add a separate public client, as shown in Client Components.

Server Components

// app/page.tsx import from "next/link"; export default async function () { const { : } = await .("blog").("-date").(["title", "slug"]).(); return ( <> {.(() => ( < ={.}> < ={`/blog/${.}`}>{.}</> </> ))} </> ); }

Calling the same query in several components (for example in generateMetadata and the page) sends one request per render: Next memoizes fetch calls with the same URL and options.

Dynamic routes and not found pages

Pre-render every entry with generateStaticParams, and turn a 404 from the CMS into Next’s not found page:

// app/blog/[slug]/page.tsx import type { Metadata } from "next"; import { } from "next/navigation"; type = { : <{ : string }> }; export async function () { const { } = await .("blog").(["slug"]).(); return .(() => ({ : . })); } async function (: string) { const = await .("blog").().(); if (!) (); return .; } export async function ({ }: ): <Metadata> { const = await ((await ).); return { : . }; } export default async function ({ }: ) { const = await ((await ).); return <>{.}</>; }

Caching per query

Options passed to .get() are merged over the client’s fetchOptions:

// always fresh await .("settings").({ : { : "no-store" } }); // cache for an hour, and tag it for on-demand revalidation await .("blog") .({ : { : { : 3600, : ["blog"] } } });

On-demand revalidation

Expire tagged responses when content changes, for example from a webhook that your CMS calls after saving an entry:

// app/api/revalidate/route.ts import { } from "next/cache"; export async function (: Request) { if (..("authorization") !== `Bearer ${..}`) { return new ("Unauthorized", { : 401 }); } ("blog", "max"); return .({ : true }); }

Client Components

Data that is fetched in the browser (search, filters, infinite lists) needs a second client that only uses public settings: a NEXT_PUBLIC_ URL, no token and no next fetch options.

// src/cms-public.ts import { } from "@headquery/statamic"; import type { Schema } from "./cms.generated"; export const = <Schema>({ : ..!, });

The Statamic REST API must be reachable from the browser for this. If it runs on another domain, allow your site’s origin in Laravel’s CORS config (config/cors.php, with api/* in paths).

Use it with a data fetching library such as TanStack Query or SWR:

// app/blog/blog-filter.tsx "use client"; import { } from "react"; import from "swr"; type = "-date" | "title"; export function () { const [, ] = (""); const [, ] = (false); const [, ] = <>("-date"); // Builders are immutable: add a filter only when it's set. let = .("blog").().(10); if () = .("title", "contains", ); if () = .("featured", true); // Same filters → same URL → same cache entry, whatever order they were set in. const { , } = (.(), () => .(), { : true }); return ( <> < ={} ={() => (..)} ="Search posts" /> <> < ="checkbox" ={} ={() => (..)} /> Featured only </> < ={} ={() => (.. as )}> < ="-date">Newest first</> < ="title">Title A–Z</> </> < ={}> {?..(() => ( < ={.}> {.} {. && "★"} </> ))} </> </> ); }

If both clients use the same baseUrl, they produce the same URL for the same query, so data fetched on the server can be handed to the client cache without remapping keys (see SWR server-side data). If the server reaches the CMS through an internal URL, the keys differ.

Last updated on