# Caching with Next.js and Agility CMS

> Source: https://agilitycms.com/docs/nextjs/caching-with-next-js-and-agility

Next.js 16 gives you two ways to cache Agility content and invalidate it on publish, and both are current:

- **Fetch-level tags.** Each Agility fetch carries a cache tag and a `revalidate` time, and routes are statically generated. This is what the [Agility Next.js Starter](https://github.com/agility/agilitycms-nextjs-starter) does today, and it's covered [at the end of this guide](#fetch-level-tags-what-the-starter-uses).
- **Cache Components** (the `"use cache"` directive). Each read is a cached function with its own tag, and routes prerender a static shell. It's more granular and less hand-tuned, and it's the model to choose for a new build that doesn't start from the starter.

Either way, your site serves static pages *and* updates the moment an editor hits Publish.

You'll build on two SDKs: the [`@agility/nextjs`](https://www.npmjs.com/package/@agility/nextjs) helpers and the underlying [`@agility/content-fetch`](https://www.npmjs.com/package/@agility/content-fetch) fetch SDK. The [Advanced Next.js Demo Site](/docs/nextjs/using-the-advanced-next-js-demo-site) and **this documentation site both run on the Cache Components model described below.**

> **Terminology.** In Agility a **Layout** (a.k.a. *Page*) is the object that represents a page on your site; you'll see "Layout" and "Page" used interchangeably. **Components** (a.k.a. *Modules*) are the content blocks placed into a page's zones.

## The whole strategy in one paragraph

Fetch every piece of CMS data through a thin **cached wrapper** that stamps the result with a stable **tag** (`agility-content-{id}-{locale}`, `agility-page-{pageID}-{locale}`, …) and caches it for a long time (`cacheLife("days")`). When an editor publishes, Agility fires a **webhook** that calls `revalidateTag()` for exactly the tags that changed, so the affected pages rebuild from fresh data on the next request, and nothing else is touched. **Preview / draft reads skip the cache entirely** so editors always see their latest work.

---

## Cache Components (Next.js 16)

### 1. Turn on Cache Components

```ts
// next.config.ts
import type { NextConfig } from "next"

const nextConfig: NextConfig = {
  // Enables the `"use cache"` directive + partial prerendering.
  cacheComponents: true,
}

export default nextConfig
```

With this on, a route prerenders its static shell at build time and streams the dynamic/uncached parts at request time, and you no longer hand-tune `export const revalidate` / `dynamic` per route.

### 2. One preview-aware SDK client

```ts
// lib/cms/getAgilitySDK.ts
import agility from "@agility/content-fetch"

// Use this variant anywhere you can't read draftMode(): inside `"use cache"`,
// in generateStaticParams, and in webhooks.
export const getAgilitySDK_NonReact = (isPreview: boolean) =>
  agility.getApi({
    guid: process.env.AGILITY_GUID!,
    apiKey: isPreview
      ? process.env.AGILITY_API_PREVIEW_KEY!
      : process.env.AGILITY_API_FETCH_KEY!,
    isPreview,
  })
```

### 3. Wrap every CMS read in `"use cache"` + a tag

Each read has two paths: **published** content is cached and tagged; **preview** content bypasses the cache.

```ts
// lib/cms/getContentItem.ts
import { cacheTag, cacheLife } from "next/cache"
import { connection } from "next/server"
import { getAgilitySDK_NonReact } from "./getAgilitySDK"

export const getContentItem = async <T>(params: {
  contentID: number
  languageCode: string
  preview?: boolean
  contentLinkDepth?: number
}) => {
  if (params.preview) {
    // preview/dev is NEVER cached: opt into a request so the prerender
    // pass doesn't try to (and abort on) this uncached fetch
    await connection()
    return fetchContentItem<T>(params)
  }
  return cachedContentItem<T>(params)
}

const cachedContentItem = async <T>(params: any) => {
  "use cache"
  cacheTag(`agility-content-${params.contentID}-${params.languageCode}`)
  cacheLife("days")
  return fetchContentItem<T>({ ...params, preview: false })
}

const fetchContentItem = async <T>(params: any) => {
  const sdk = getAgilitySDK_NonReact(params.preview === true)
  return sdk.getContentItem({
    contentID: params.contentID,
    languageCode: params.languageCode,
    contentLinkDepth: params.contentLinkDepth ?? 1,
  })
}
```

Write the same wrapper for the other read types, each with its own tag:

| Wrapper | Tag |
| --- | --- |
| `getContentItem` | `agility-content-{contentID}-{locale}` |
| `getContentList` | `agility-content-{referenceName}-{locale}` |
| `getPage` / `getAgilityPage` | `agility-page-{pageID}-{locale}` |
| `getSitemapFlat` | `agility-sitemap-flat-{locale}` |

> **Why `connection()` for preview?** Under Cache Components, an *uncached* fetch that runs during the prerender pass aborts the build. `connection()` (from `next/server`) marks that branch as request-time/dynamic so the uncached preview fetch is allowed. Keep any `connection()` call inside a `<Suspense>` boundary, or Next throws a "blocking-route" error.

### 4. Compose pages from the cached primitives

Resolve a page from the cached **sitemap → node → page-by-ID** rather than `getAgilityPageProps` (whose fetch options predate Cache Components):

```ts
// app/[locale]/[...slug]/page.tsx (sketch)
const sitemap = await getSitemapFlat({ locale, preview })   // cached + tagged
const node = sitemap["/" + slug.join("/")]
if (!node) notFound()
const page = await getPage({ pageID: node.pageID, locale, preview })  // cached + tagged
```

Each primitive carries its own tag, so a page's static output is tied to the exact content + sitemap tags it consumed. Publish any of them and only the pages that read it rebuild. For an item or a component that's a handful of pages. For the sitemap it's every page: see [Tags that every page carries](#7-tags-that-every-page-carries).

### 5. Invalidate instantly on publish (the webhook)

```ts
// app/api/revalidate/route.ts
import { revalidateTag, revalidatePath } from "next/cache"
import { NextRequest, NextResponse } from "next/server"

const EXPIRE_NOW = { expire: 0 }

export async function POST(request: NextRequest) {
  const p = await request.json()
  const locale = p.languageCode
  const revalidated: string[] = []

  // content item / list
  if (p.contentID) {
    revalidateTag(`agility-content-${p.contentID}-${locale}`, EXPIRE_NOW)
    revalidated.push(String(p.contentID))
  }
  if (p.referenceName) {
    revalidateTag(`agility-content-${p.referenceName.toLowerCase()}-${locale}`, EXPIRE_NOW)
  }

  // page / layout
  if (p.pageID) {
    revalidateTag(`agility-page-${p.pageID}-${locale}`, EXPIRE_NOW)
    // a page publish can add, move or rename a URL
    revalidateTag(`agility-sitemap-flat-${locale}`, EXPIRE_NOW)
    // resolve the path from a FRESH sitemap, then revalidatePath(node.path)
  } else if (!p.contentID && !p.referenceName) {
    // Neither an item nor a page: a URL Redirection change, which carries no
    // contentID or pageID. If your redirects are generated at build time
    // (next.config.ts redirects()), this is where you rebuild them.
    if (process.env.BUILD_HOOK_URL) {
      await fetch(process.env.BUILD_HOOK_URL, { method: "POST", signal: AbortSignal.timeout(10_000) })
      revalidated.push("build-hook")
    }
  }

  return NextResponse.json({ revalidated, at: new Date().toISOString() })
}
```

Four things to note:

- **Expire what was published.** `revalidateTag(tag, { expire: 0 })` expires a tag, so the next request renders fresh data. The Next.js docs name this form for webhooks. `revalidateTag(tag, "max")` only marks the tag stale: the next request gets the old entry while a fresh one renders in the background, and the first request after a publish is usually the editor checking their change. Use `{ expire: 0 }` for the tags of whatever was published, and keep `"max"` for tags that many pages share ([step 7](#7-tags-that-every-page-carries)). The one-argument `revalidateTag(tag)` is deprecated.
- **Redirect changes arrive with no `contentID` or `pageID`.** That's the `else` branch. Redirects compiled into `next.config.ts` only change on a build, so trigger one through your host's build hook (set it as `BUILD_HOOK_URL`). The hook only queues a build, so give the call a timeout rather than holding Agility's webhook open. If you read redirects at request time instead, revalidate their cache tag there. See [Implementing URL Redirects with Next.js](/docs/nextjs/implementing-url-redirects-with-next-js).
- Configure it in Agility under **Settings → Webhooks**: point a *publish* (and *unpublish*) webhook at `POST https://your-site.com/api/revalidate`.
- **You only need a path if something caches by URL**, such as a CDN in front of your site. Tags already cover the Next.js cache. To purge a URL, look it up in the flat sitemap: by `pageID` for a page event, and by `contentID` for an item in a dynamic page's list, since publishing one item sends a content event with no `pageID`. See [Finding the URL that changed](/docs/developers/webhook-events-and-payloads#finding-the-url-that-changed).

Keep the tag strings in your `lib/cms/*` wrappers and in this route **in lockstep**. They are a contract. A typo means "published but never refreshes."

### 6. `contentLinkDepth`: how granular do you want invalidation?

When you fetch a Layout with `contentLinkDepth: 0`, the page props contain only the **contentID** of each component, and you then fetch each component through its own cached wrapper. That means a component's content is cached (and invalidated) **independently** of the page it sits on: edit one component, and only that component's tag clears. Higher depths (the default `1`) are simpler but couple a component's freshness to the page fetch. For most sites, depth `0` + per-component caching gives the best editor experience.

### 7. Tags that every page carries

Step 4 has every page read the flat sitemap, so every page carries `agility-sitemap-flat-{locale}`. Any list that every page of a kind reads does the same: a blog post list used for "related posts" puts its tag on every post. Expiring one of these tags empties the cache for all of those pages, and each one renders from scratch on its next request.

This bites as soon as you add dynamic pages. A new blog post's URL only exists in the sitemap, so the obvious fix is to expire the sitemap tag on every content publish. It works, and it also re-renders the whole site after every post. On agilitycms.com, after a run of post publishes, pages that had answered in 150 to 350 ms took 2 to 5 seconds until each had been visited again.

Expire a shared tag only when the set of pages has changed:

| What was published | The item's own tag | Sitemap and shared list tags |
| --- | --- | --- |
| A page: published, moved, unpublished or deleted | expire | expire |
| A shared or component item (it has no page of its own) | expire | leave alone |
| A dynamic page item whose URL already answers 200 | expire | mark stale (`"max"`) |
| A new dynamic page item, or one whose slug changed | expire | expire |

The third row is the common one, and it's easy to detect: find the item in a fresh copy of the flat sitemap, then ask your own site for that path **before** you revalidate anything. If it answers 200, the cached sitemap already has the URL, so the page list hasn't changed.

```ts
// app/api/revalidate/route.ts (excerpt): replaces step 5's content item / list branch
const isLive = async (path: string) => {
  try {
    const res = await fetch(new URL(path, process.env.SITE_URL), {
      method: "HEAD",
      redirect: "manual", // a redirect means the URL moved: treat it as changed
      cache: "no-store",
      signal: AbortSignal.timeout(5000),
    })
    return res.status === 200
  } catch {
    return false // can't tell: expire, which is always safe
  }
}

/** Does this list feed a dynamic page? True if any of its items has a page. */
const listHasPages = async (referenceName: string | undefined, sitemap: Record<string, { contentID?: number }>) => {
  if (!referenceName) return true // can't tell: expire
  const list = await getAgilitySDK_NonReact(false).getContentList({ referenceName, languageCode: locale, take: 10 })
  const withPages = new Set(Object.values(sitemap).map((node) => node.contentID))
  return list.items.some((item) => withPages.has(item.contentID))
}

if (p.contentID && p.state === "Published") {
  // uncached, so a post published seconds ago is in it
  const sitemap = await fetchSitemapFlat({ channelName, languageCode: locale, preview: false })
  const ownPath = Object.keys(sitemap).find((path) => sitemap[path].contentID === p.contentID)

  // Decide first: once the item's own tag has expired, the HEAD request
  // costs a full render of that page.
  const shared = ownPath
    ? (await isLive(ownPath)) ? "max" : EXPIRE_NOW
    : (await listHasPages(p.referenceName, sitemap)) ? EXPIRE_NOW : null // null: a shared item

  if (shared) revalidateTag(`agility-sitemap-flat-${locale}`, shared)
  if (p.referenceName) revalidateTag(`agility-content-${p.referenceName.toLowerCase()}-${locale}`, shared ?? EXPIRE_NOW)
  revalidateTag(`agility-content-${p.contentID}-${locale}`, EXPIRE_NOW)
}
```

A few things to know:

- **An item missing from the fresh sitemap may still be a new page.** The sitemap can lag a publish by a few seconds. That's why `listHasPages` checks the item's list: if other items in it have pages, this one is a new page and the sitemap tag expires.
- **`"max"` is cheaper, not free.** A stale tag still re-renders every page that carries it, one request at a time, in the background. Hosts that purge their CDN by cache tag, such as Netlify, also drop those pages from the CDN, so each page's next request reaches your function. It answers from the stale entry instead of rendering from scratch.
- **To avoid the fan-out altogether, don't put the sitemap tag on every page.** Resolve a URL with a lookup cached per path, so publishing a post touches the post and the pages that list it, and nothing else. It's more work, and it's the fix to reach for when you publish often.

---

## Cache Components gotchas

- **Non-determinism aborts the prerender.** `Date.now()`, `Math.random()`, or `new Date()` in a component *outside* a `"use cache"` scope fails the build with `next-prerender-random`. Isolate the non-deterministic read inside a `"use cache"` function, or push it behind `connection()`.
- **`connection()` must live inside `<Suspense>`.** Otherwise you get a "blocking-route" error. Wrap request-time chrome (preview scripts, draft-mode header data) in its own boundary.
- **Preview / dev must bypass the cache.** The `connection()` branch in each wrapper is what lets editors see unpublished drafts on the preview deploy and at `npm run dev`.
- **A bulk publish leaves the site cold.** Publishing many dynamic page items in a row sends many pages back to your functions, even with [step 7](#7-tags-that-every-page-carries). Don't measure page speed or start an SEO crawl straight after one. Give the cache time to refill, or warm it by requesting each URL in your sitemap once.

---

## Fetch-level tags (what the starter uses)

Without Cache Components, the App Router caches tagged `fetch` calls. The Agility Next.js Starter sets the tag and a 60-second revalidation on the SDK's fetch options in each `lib/cms/` helper:

```ts
// lib/cms/getContentItem.ts (starter)
agilitySDK.config.fetchConfig = {
  next: {
    tags: [`agility-content-${params.contentID}-${params.languageCode || params.locale}`],
    revalidate: 60,
  },
}
```

and statically generates its catch-all route, re-rendering a path at most every 60 seconds:

```ts
// app/[...slug]/page.tsx (starter)
export const revalidate = 60
export const dynamic = "force-static"
```

The starter's `app/api/revalidate/route.ts` webhook clears the same tag names with the two-argument `revalidateTag(tag, "max")`, so a publish shows up on the next request instead of waiting for the 60 seconds to pass. Don't combine these route segment configs with `cacheComponents: true`: Next.js rejects them when Cache Components is on.

---

## Summary

For Cache Components:

1. `cacheComponents: true`.
2. One preview-aware SDK client (`getAgilitySDK_NonReact`).
3. Every CMS read = a `"use cache"` wrapper with a stable `cacheTag` + `cacheLife("days")`; preview bypasses via `connection()`.
4. Compose pages from those cached primitives, not `getAgilityPageProps`.
5. An Agility publish webhook expires the tags of whatever was published (`{ expire: 0 }`) and marks tags that every page carries stale (`"max"`) when the set of pages hasn't changed.

That's the whole model: long-lived caches, surgical invalidation, instant editor updates.

---

## Related pages

- [Using the Next.js Starter](https://agilitycms.com/docs/nextjs/using-the-next-js-blog-starter.md)
- [How the Next.js Starter Works](https://agilitycms.com/docs/nextjs/how-the-next-js-starter-works.md)
- [Preview URL Lifecycle](https://agilitycms.com/docs/nextjs/preview-url-lifecycle.md)

Index of every docs page: https://agilitycms.com/docs/llms.txt
