# Large Sitemaps in Next.js

> Source: https://agilitycms.com/docs/nextjs/large-sitemaps-in-next-js

Most Agility Next.js sites resolve a URL by reading the flat sitemap and looking up the path. That's fine for a few hundred pages. On a large site it becomes the most expensive thing your app does, and it can run your functions out of memory. This guide shows how to tell whether you're affected and how to fix it without changing what your site renders.

## Are you affected?

Download your flat sitemap and count it:

```bash
curl -s -H "APIKey: $AGILITY_API_FETCH_KEY" \
  "https://api.aglty.io/$AGILITY_GUID/fetch/en-us/sitemap/flat/website" \
  | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s),n=Object.values(j);console.log("bytes",s.length,"nodes",n.length,"dynamic",n.filter(x=>x.contentID>0).length)})'
```

(Use your instance's API host if it isn't `api.aglty.io`; see [Content Fetch API](/docs/developers/content-fetch-api).)

Look at the node count, not the number of pages your editors made. **Every dynamic page adds one node per item in its list**, so a list shown under several dynamic pages is counted several times. For example, 2,036 articles each listed under 15 section pages makes 30,540 nodes. If you have more than a few thousand nodes, or the JSON is over about 1 MB, read on.

Symptoms: function out-of-memory errors or timeouts under load (crawlers, a full-site link check), slow uncached renders (several seconds) and high CPU while rendering.

## Why it happens

Next.js caches don't hand you the stored object. They hand you a **copy**:

- A `"use cache"` hit decodes the stored stream into a new object.
- A fetch-cache hit returns the response body, and `.json()` parses it again.

So code like this builds the entire sitemap on every call, even when the cache is warm:

```ts
const sitemap = await getSitemapFlat({ locale, preview }) // cached, but a new 13 MB object every time
const node = sitemap[path]
```

A typical page calls it several times: in `generateMetadata`, in the page, for breadcrumbs or JSON-LD, and to resolve listing URLs. Under concurrency, those copies add up to gigabytes. The sitemap entry also fills Next's 50 MB in-memory cache, pushing out everything else.

## The fix: one index per process, single-node lookups

1. **Download the sitemap once per server process** and reduce it to a compact index. Dynamic nodes that share a list repeat the same title and name, so store each item's text once and keep per-section exceptions. Keep any node that doesn't fit the pattern whole, so nothing is lost.
2. **Read one node at a time.** Wrap each lookup (node by path, the home path, node by page ID and content ID, a short list for `sitemap.xml`) in its own cached function. A cached node is a few hundred bytes, so a cache hit costs almost nothing.
3. **Keep your existing cache tag.** Tag the lookups with `agility-sitemap-flat-{locale}`, so the publish webhook still clears them.

The [Advanced Next.js Demo Site](/docs/nextjs/using-the-advanced-next-js-demo-site) ships this as `src/lib/cms/sitemapIndex.ts` (the index) and `src/lib/cms/getSitemapNode.ts` (the lookups). The [Next.js starter](/docs/nextjs/how-the-next-js-starter-works) ships the same index for its fetch-cache model, as `lib/cms/sitemapIndex.ts` and `lib/cms/getSitemapIndex.ts`. A sketch of the lookup side, simplified from the demo site:

```ts
// lib/cms/getSitemapNode.ts (sketch)
import { cacheLife, cacheTag } from "next/cache"
import { getPublishedSitemapIndex } from "./sitemapIndex"

// A tiny cached token under the sitemap tag. When the publish webhook
// revalidates the tag, the next read gets a new token.
const sitemapVersion = async (locale: string) => {
  "use cache"
  cacheTag(`agility-sitemap-flat-${locale}`)
  cacheLife("days")
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
}

const cachedNode = async (locale: string, path: string, version: string) => {
  "use cache"
  cacheTag(`agility-sitemap-flat-${locale}`)
  cacheLife("days")
  const index = await getPublishedSitemapIndex(locale, version) // one download per process per version, not per call
  return index.get(path) ?? null
}

export const getSitemapNode = async ({ locale, path }: { locale: string; path: string }) =>
  cachedNode(locale, path, await sitemapVersion(locale))
```

`getPublishedSitemapIndex` keeps the index in module scope and downloads the sitemap again only when the version token changes, which happens when the publish webhook clears the sitemap tag. Concurrent requests share one in-flight download. The webhook also drops the index on the instance it reaches, so that instance refreshes straight away. The starter refreshes on a timer instead, every `AGILITY_FETCH_CACHE_DURATION` seconds (default 60), and serves the previous index while a refresh runs. In both, preview reads skip all of this and download fresh, once per request, so editors see new pages straight away.

Then replace every whole-sitemap read in your render path:

| Before | After |
|---|---|
| `sitemap[path]` in `getAgilityPage` | `getSitemapNode({ locale, path })` |
| `findHomeNode(sitemap)` | `getHomePath(locale)` |
| hreflang / language switcher: scan for `pageID` + `contentID` | `findSitemapPath({ locale, pageID, contentID })` |
| `sitemap.xml`, `llms.txt`, `generateStaticParams` | one cached list of paths, filtered inside the cached function |
| listing cards: scan the sitemap for each item's URL | look up only the listed items |

Also check the proxy or middleware. If it validates paths against the sitemap, point it at the same in-process index rather than keeping its own copy. The demo's proxy can't use the Next.js cache, so it reloads the index every 60 seconds and keeps the previous one if a reload fails.

## Prove nothing changed

Build the previous commit and the new one, run both with `next start`, and compare the HTML of a few hundred URLs: pages, dynamic items, listings with paging and filters, 404s, and paths in a different case. Ignore Next's build-specific chunk names. When we moved large sites to this pattern, every URL matched. The only difference was the order of URLs in one site's `sitemap.xml`, which search engines ignore.

To check the index itself, the demo site's `scripts/test-sitemap-index.ts` asserts that it rebuilds every sitemap node exactly, in order. Run `npx tsx scripts/test-sitemap-index.ts`, or add `live` to also check each configured locale's live sitemap.

## While you're there

- **Use a strict fetch client.** `@agility/content-fetch` returns `undefined` for a 5xx, a timeout or a network error, the same as for a real 404. Under load, one failed request can be cached as a 404 page. Make anything other than a 404 throw, so the failure isn't cached and the next request retries. See [Fetch API Status Codes and Caching](/docs/developers/fetch-api-status-codes-and-caching). Both the demo site and the starter include `strictClient.ts`.
- **Cards don't need bodies.** A listing page that reads 50 full articles downloads and caches every body. Ask for only the card's fields with the Fetch API's [`fields` parameter](/docs/javascript/content-fetch-js-sdk#fields). Read lists in pages of 50 or fewer and stop once you have enough.

## Related

- [Caching with Next.js and Agility](/docs/nextjs/caching-with-next-js-and-agility)
- [Using the Advanced Next.js Demo Site](/docs/nextjs/using-the-advanced-next-js-demo-site)
- [Fetch API Status Codes and Caching](/docs/developers/fetch-api-status-codes-and-caching)

---

## Related pages

- [Multi-Locale Support with Next.js](https://agilitycms.com/docs/nextjs/multi-locale-support-with-next-js.md)
- [Google Analytics and Next.js](https://agilitycms.com/docs/nextjs/google-analytics-and-next-js.md)
- [Deploying Next.js to Vercel](https://agilitycms.com/docs/nextjs/deploying-next-js-to-vercel.md)
- [Deploying Next.js to Netlify](https://agilitycms.com/docs/nextjs/deploying-next-js-to-netlify.md)
- [Deploying Next.js on Azure](https://agilitycms.com/docs/nextjs/deploying-next-js-on-azure.md)
- [Using Storybook.js with Agility CMS and Next.js](https://agilitycms.com/docs/nextjs/using-storybook-js-with-agility-cms-and-next-js.md)
- [Rendering & Data Fetching with Next.js](https://agilitycms.com/docs/nextjs/next-js-and-server-side-rendering.md)
- [Implementing Pagination with Next.js](https://agilitycms.com/docs/nextjs/implementing-pagination-with-next-js.md)
- [Implementing URL Redirects with Next.js](https://agilitycms.com/docs/nextjs/implementing-url-redirects-with-next-js.md)
- [Implementing a Custom 404 Page with Next.js](https://agilitycms.com/docs/nextjs/implementing-a-custom-404-page-with-next-js.md)
- [Implementing JSON-LD Structured Data with Next.js](https://agilitycms.com/docs/nextjs/implementing-json-ld-structured-data-with-next-js.md)
- [Using the AgilityPic Component for Responsive Images](https://agilitycms.com/docs/nextjs/using-the-agilitypic-component-for-responsive-images.md)

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