Skip to main content

Getting Started with Cache Components and OSR

How to make a Next.js 16 and Sitecore Content SDK site fast, and fresh the moment content is published.

Updated 11 min readMarkdown
Getting Started with Cache Components and OSR

If your Sitecore pages are slow because every visit calls Experience Edge, or stale because they only refresh on a timer, this guide is for you. It explains Cache Components and on-demand static revalidation (OSR) in plain terms, then walks through setup step by step.

This guide assumes Next.js 16, the App Router, and Content SDK 2.2 or later. Read it once from start to finish before you change any code. It takes about 15 minutes.


The short version

Cache Components let you choose what gets saved, using the 'use cache' directive. You decide how long it is saved with cacheLife. You label saved data with cacheTag so you can find it later. When an editor publishes in Sitecore, a webhook calls your site's /api/revalidate endpoint, which marks the matching saved pages as stale. The next visitor sees the saved page right away, and the page refreshes in the background.

The result: fast pages, fresh content after publish, and no redeploy. If you ever need to refresh content by hand, Vercel can purge the same tags from its dashboard, CLI, or REST API.


Five terms you need

Term What it means in plain English
'use cache' "Save the result of this function."
cacheLife "Keep the saved result for this long."
cacheTag "Attach a label so I can find this saved result later."
revalidateTag "Mark everything with this label as out of date."
Profile "How out of date is acceptable." The two you need are 'max' and { expire: 0 }.

Here is where each term appears in a helper. The highlighted lines are the parts you write.

Anatomy of a cached function, with callouts for use cache, cacheLife, cacheTag and revalidateTag

Figure 1. A cached helper function. The webhook route calls revalidateTag later, with the same label.


How the pieces fit together

Two paths work together. The read path serves visitors quickly. The publish path keeps the cache up to date.

Read path: most requests are served from the Next.js cache, and only misses reach Experience Edge

Figure 2. Read path. Most requests are served from the cache. Only misses reach Experience Edge.

Publish path: an editor publishes, Experience Edge sends a webhook, the route calls revalidateTag

Figure 3. Publish path. A publish marks matching cache entries stale. No redeploy is needed.


Step 0: Choose your approach

What you need What to use
Content can be a few minutes to a few hours out of date Cache Components with cacheLife. No webhook.
Content must update as soon as it is published Cache Components with the OSR webhook.
Output must never be cached (per-visitor or time-sensitive) Leave it dynamic.

Editing and preview always stay dynamic. You do not need to cache them.


Step 1: Turn on Cache Components

Open next.config.ts and add the flag:

import type { NextConfig } from 'next';
 
const nextConfig: NextConfig = {
  cacheComponents: true,
  // ...your existing settings
};
 
export default nextConfig;

If you already wrap this config in plugins, such as next-intl, keep those wrappers and add the flag to the config object they receive.


Step 2: Remove route settings that conflict

With Cache Components on, route files cannot export the old caching settings. If the build fails, check for these lines and delete them:

export const dynamic = 'force-dynamic';   // delete
export const revalidate = 3600;           // delete
export const fetchCache = 'default-cache'; // delete

Also check generateStaticParams. Do not let it return an empty array, because Cache Components can fail the build when it does.


Step 3: Use the cache helpers

The Content SDK template includes three helper functions in src/lib/cache/:

  • getSitecorePage, for page layouts
  • getSitecoreDictionary, for translations
  • getSitecoreErrorPage, for 404 and error pages Here is getSitecorePage, taken from the template:
// src/lib/cache/get-sitecore-page.ts
import { collectSitecorePageCacheTags, Page } from '@sitecore-content-sdk/nextjs';
import { cacheTag } from 'next/cache';
import client from 'src/lib/sitecore-client';
 
type GetSitecorePageParams = {
  site: string;
  locale: string;
  path: string[];
};
 
export async function getSitecorePage(params: GetSitecorePageParams): Promise<Page | null> {
  'use cache';
 
  const { site, locale, path } = params;
  const page = await client.getPage(path, { site, locale });
 
  const tags = collectSitecorePageCacheTags({
    site,
    locale,
    path: client.parsePath(path),
    route: page?.layout?.sitecore?.route,
  });
 
  for (const tag of tags) {
    cacheTag(tag);
  }
 
  return page;
}

What this does:

  1. 'use cache' tells Next.js to save the result.
  2. The Sitecore call fetches the page layout.
  3. The helper creates tags for the route and the page item, then attaches them to the saved result. Here is how one published item reaches the cached pages through those tags:
Tag map: a published item connects to cache tags, which connect to cached pages

Figure 4. Publishing the Products page marks only /products and its variants as stale.

Now use the helper in your page. Replace the direct client.getPage call. Keep your existing preview code unchanged:

const draft = await draftMode();
const page = draft.isEnabled
  ? await client.getPreview(previewData) // your existing preview code, unchanged
  : await getSitecorePage({ site, locale, path: path ?? [] });

Do the same for translations in src/i18n/request.ts, using getSitecoreDictionary. Then turn off the SDK's built-in dictionary cache, so it does not compete with this one. In sitecore.config.ts:

dictionary: { caching: { enabled: false } },

Do not add 'use cache' to the page component itself. Put it on the helper functions.


Step 4: Add a time backstop

Tags handle publishing. A time limit handles anything a webhook misses. Add cacheLife inside the helper, right after 'use cache':

import { cacheLife } from 'next/cache';
 
export async function getSitecorePage(params: GetSitecorePageParams): Promise<Page | null> {
  'use cache';
  cacheLife('hours');
 
  // ...the rest of the function is unchanged
}

'hours' is a built-in profile. Check the Next.js cacheLife documentation for its exact timings. Without an explicit cacheLife, Next.js uses its default profile.


Step 5: Add the revalidation endpoint

The template creates this file for you. It is the endpoint your webhook will call:

// src/app/api/revalidate/route.ts
import { createSitecoreRevalidateRouteHandler } from '@sitecore-content-sdk/nextjs/route-handler';
import type { SiteInfo } from '@sitecore-content-sdk/nextjs';
import scConfig from 'sitecore.config';
import sites from '.sitecore/sites.json';
 
export const { POST } = createSitecoreRevalidateRouteHandler({
  defaultLocale: scConfig.defaultLanguage,
  sites: sites as SiteInfo[],
});

Set a secret in every environment you deploy to:

SITECORE_REVALIDATE_SECRET=use-a-long-random-value

If this variable is empty, anyone can call the endpoint. Set it in production.

Choose the profile

By default, the handler uses the 'max' profile. Here is what each option means for the first visitor after a publish:

Profile First visitor after publish Second visitor onward
'max' (default) Gets the old page instantly. The new page builds in the background. Gets the new page.
{ expire: 0 } Waits while the new page builds. Gets the new page.
Timeline comparing max and expire 0 for the first visitors after a publish

Figure 5. For the first visitor after a publish, 'max' serves the old page instantly. { expire: 0 } makes that visitor wait for the new page.

If stale content for one visitor is not acceptable, switch to { expire: 0 }:

export const { POST } = createSitecoreRevalidateRouteHandler({
  defaultLocale: scConfig.defaultLanguage,
  sites: sites as SiteInfo[],
  cacheProfile: { expire: 0 },
});

Step 6: Register the webhook

Register one webhook per environment, pointing at that environment's HTTPS address. The example below shows the general shape of the request. Confirm the endpoint and the execution mode in Sitecore's Admin REST API documentation before you rely on them.

POST https://edge.sitecorecloud.io/api/admin/v1/webhooks
Authorization: Bearer <your JWT>
 
{
  "label": "prod-revalidate",
  "uri": "https://www.example.com/api/revalidate",
  "method": "POST",
  "executionMode": "OnUpdate",
  "headers": {
    "x-revalidate-secret": "<same value as SITECORE_REVALIDATE_SECRET>"
  }
}

OnUpdate includes the IDs of the items that changed, which the handler needs. Sitecore's general webhook documentation describes OnEnd as the default. Check which mode SitecoreAI Experience Edge uses in your environment.


Step 7: Test it

Test with a production build. Development mode does not reproduce the cache behavior.

  1. Run next build, then next start.
  2. Load a page. It is now cached.
  3. Publish a change to that page in Sitecore.
  4. Load the page. With the default 'max' profile, you may see the old content once. That is expected.
  5. Load it again. You should see the new content. You can also call the endpoint yourself to test the tags:
curl -X POST https://your-site.example.com/api/revalidate \
  -H "Content-Type: application/json" \
  -H "x-revalidate-secret: $SITECORE_REVALIDATE_SECRET" \
  -d '{"tags":["sc:route:default:en:about"]}'

A successful response includes "revalidated": true and a tagsCount. If tagsCount is 0 after a publish, the webhook's tags probably do not match the tags on your cached pages. Check the tag format first.


Manual revalidation on Vercel

The webhook handles publishing automatically. You can also purge cache tags by hand. This helps after a bulk migration, when a webhook fails, or when one page needs an immediate refresh.

Vercel gives you three ways to do it:

  • Dashboard. Open your project, go to CDN → Caches → Purge cache, choose Cache Tag, enter a tag such as products, and choose Invalidate.
  • CLI. Run vercel cache invalidate --tag products.
  • REST API. Send a POST request to /v1/edge-cache/invalidate-by-tags:
curl -X POST "https://api.vercel.com/v1/edge-cache/invalidate-by-tags?projectIdOrName=YOUR_PROJECT&teamId=YOUR_TEAM_ID" \
  -H "Authorization: Bearer $VERCEL_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"tags":["products"],"target":"production"}'
Manual and automatic invalidation on Vercel: triggers feed one cache tag, which clears the CDN cache, Runtime Cache, and Data Cache

Figure 6. Automatic and manual triggers act on tagged entries. A Vercel tag purge reaches the CDN cache, Runtime Cache, and Data Cache together.

Keep these rules in mind:

  • Use Invalidate, not Delete. Invalidate serves the stale copy while the cache refreshes. Delete makes every request wait for the origin, which can cause a traffic spike.
  • One tag purge covers three layers. It clears the CDN cache, Runtime Cache, and Data Cache together.
  • Use * sparingly. In the dashboard, * purges the whole project.
  • Respect the limits. A bulk REST call accepts up to 16 tags. Purge calls are rate limited, so batch tags where you can.
  • Test your own tags. Whether a purge reaches a given Next.js cache entry depends on how that entry is cached and tagged. Check the request logs for STALE with the reason "Tag-based invalidation" to confirm.

Common mistakes

  • The build fails with a message about dynamic, revalidate or fetchCache. Remove those exports from the route files.
  • The build fails on generateStaticParams. Make sure it never returns an empty array.
  • Pages show old translations. Confirm that dictionary.caching.enabled is false.
  • Preview shows cached content. Keep the preview branch calling Sitecore directly. Do not route it through the cache helpers.
  • The endpoint accepts anonymous calls. Set SITECORE_REVALIDATE_SECRET in every production environment.
  • Invalidation works on one server but not another. With several server instances or containers, the default in-memory cache is per process. Each instance needs a shared cache handler, such as Redis, or invalidation only reaches one instance. See Next.js's cacheHandlers documentation.
  • You expect the first visitor after a publish to see the new content. With 'max', they see the old page once. Use { expire: 0 } if that is not acceptable.
  • You try to refresh a single personalization variant. You cannot. All variants of a page share the same item tag, so publishing refreshes them together.
  • You are on serverless hosting and see slow first loads. In-memory cache entries often do not survive between requests. Check what your hosting platform provides.

What you gain

Visitors are served from the cache, so most requests never reach Experience Edge. This matters because Edge applies a fair-use limit on uncached requests. Sitecore's Accelerate recipe cites 80 per second, but that recipe is older, so confirm the current limit with Sitecore.

Pages regenerate one at a time, on demand. A publish does not need a rebuild or a redeploy. Only the pages carrying the changed item's tags are marked stale.

There is one trade-off. If you prerender every page at build time, large sites build slowly. Setting generateStaticPaths: false in sitecore.config.ts defers those pages to their first request. That makes builds faster and the first visit to each page slower.

References

No comments yet. Be the first to comment.