DatoCMS Cache Tags and Next.js
Next.js has several caching models, depending on the particular version and router used. Invalidation is traditionally tricky, with time-based invalidations not granular enough and whole-site rebuilds too slow.
Instead, invalidation via Next.js cache tags can be a powerful, highly-granular way of targeting specific pieces of content (like a route, page, or component) and only when they actually change. It allows DatoCMS to push a webhook to tell Next to invalidate only the affected content.
However, to make DatoCMS Cache Tags play well with the Next.js ones, we need a mapping layer in between because a DatoCMS record uses more cache tags than Next.js can support.
This guide details why that is necessary and how it works. It covers Next.js versions 15.x and 16.x
Due to limitations in the framework, a Next.js cache entry can hold at most 128 cache tags, below what DatoCMS needs.
Past the limit, Next.js silently drops the extra tags and the invalidation doesn't properly clear all the changed content.
Next.js keeps at most 128 tags per
fetch()and percacheTag()call.Vercel stores at most 128 tags per item in its Data Cache and per response in its CDN cache.
Instead, you must tag each Next.js query with only one ID, and keep the "query ID → DatoCMS Cache Tags" map in a database. That's what this guide details.
Preamble: How do Next.js cache tags work?
This diagram provides a summary of the essential steps for understanding on-demand revalidation in Next.js through cache tags:

When the browser requests a page, Next.js by default, responds with a Cache-Control: public, max-age=0, must-revalidate header. This tells the browser to always verify from the server if a newer version of the page is available. If there's no change, the server responds with the status 304, therefore saving bandwidth and time. This is referred to as the "revalidate" pattern.
The first time the browser requests a page, both the Full route cache and the Data cache will be empty, resulting in two MISS answers that trigger the fetch() requests contained in your routes. The results of those fetch() calls will be stored and tagged in Next.js Data Cache. After that, the entire page will be stored in the Next.js Full Route Cache, and marked with the same set of cache tags.
Once the cache has been created, Next.js will be able to answer the following requests with the pre-rendered result and no execution of code, until a revalidateTag() is invoked (for instance, due to a route handler connected to a webhook). In this case, the cache will be cleared and the process will restart from the beginning.
How to implement DatoCMS Cache Tags with Next.js
The basic idea
Implement a function — i.e.,
executeQuery()— responsible for executing a GraphQL query using the DatoCMS Content Delivery API, and caching the result.To be able to invalidate this request later, tag the cache entry with a single tag: the "Query ID". It is a hash of the query and its variables, so it is unique for each query.
Before returning the result of the query,
executeQuery()reads theX-Cache-Tagsheader in the response, and saves the "Query ID → DatoCMS Cache Tags" mappings in a database.
Implement a route handler listening for "Cache Tag Invalidation" events. The route needs to:
Parse the cache tags out of the DatoCMS webhook payload.
Search the database for all the Query IDs rows linked to these cache tags.
Use Next.js's
revalidateTag()to invalidate all the identified Query IDs.Delete those rows so the next execution of each query can store their proper tags.
Each query now carries just one tag (its own Query ID), far below the limit, however much content the queries return. We've created a one-to-many mapping of queries to cache tags, mapped inside our database.
Expire the cache immediately
When the webhook invalidates a query, the next visitor must get the new content. Expire the cached entries right away:
Next.js 16: call
revalidateTag(queryId, { expire: 0 }). Theexpireargument is new as of 16.Next.js 15: call
revalidateTag(queryId). On Next.js 15,revalidateTag()takes only one argument (no explicitexpire), and always expires the entries immediately.
With an immediate expiry, any visitor after the invalidation will see the fresh content (at the cost of a small wait to warm that page). Without this, the first visitor would still see a stale copy (basically the incremental static regeneration pattern).
Your own editors can use this to their advantage, AND help visitors at the same time. If they open the page to check their changes right after an invalidation, they should see the new version after the page loads. They also also re-warm the cache for other visitors in their region (who are served by the same data center).
The database
The map needs a small, persistent database that all your server instances share. Great options are Turso or a Postgres database from the Vercel Marketplace.
One table with two columns is enough:
CREATE TABLE IF NOT EXISTS query_cache_tags ( query_id TEXT NOT NULL, cache_tag TEXT NOT NULL, PRIMARY KEY (query_id, cache_tag));The code below uses three helpers that read and write this table: storeQueryCacheTags(), queriesReferencingCacheTags() and deleteQueries(). You can copy them from lib/database.ts of our starter, together with lib/cache-tags.ts: it parses the X-Cache-Tags header, and defines the CacheTag type that the helpers use.
Next.js 16
Next.js 16 can cache data in two ways:
With Cache Components (
cacheComponents: true), you cache a function with the'use cache'directive.create-next-appturns this on by default for new apps.Without Cache Components, you cache each
fetch()call, as on Next.js 15.
With Cache Components
Enable the flag:
import type { NextConfig } from 'next';
const nextConfig: NextConfig = { cacheComponents: true, partialPrefetching: true,};
export default nextConfig;Then tag each query with its Query ID, and store its DatoCMS Cache Tags:
import { createHash } from 'node:crypto';import { rawExecuteQuery } from '@datocms/cda-client';import type { TadaDocumentNode } from 'gql.tada';import { print } from 'graphql';import { cacheLife, cacheTag } from 'next/cache';import { draftMode } from 'next/headers';import { parseXCacheTagsResponseHeader } from './cache-tags';import { storeQueryCacheTags } from './database';
export async function executeQuery<Result, Variables>( query: TadaDocumentNode<Result, Variables>, variables?: Variables,): Promise<Result> { 'use cache';
// Keep the entry until the webhook invalidates it cacheLife('max');
// In draft mode, Next.js runs this function on every request and does not cache it const { isEnabled: includeDrafts } = await draftMode();
const queryId = createHash('sha1') .update(print(query)) .update(JSON.stringify(variables) || '') .digest('hex');
// One tag per query, whatever the number of DatoCMS Cache Tags cacheTag(queryId);
const [data, response] = await rawExecuteQuery(query, { token: process.env.DATOCMS_API_TOKEN!, variables, includeDrafts, returnCacheTags: true, // 'use cache' is the only cache layer: without this, Next.js can also keep the // response in its Data Cache, where revalidateTag(queryId) doesn't reach it requestInitOptions: { cache: 'no-store' }, });
// This code runs only on a cache miss: exactly when the tags can change. // Draft renders are never cached, so their tags don't need storing. if (!includeDrafts) { const cacheTags = parseXCacheTagsResponseHeader(response.headers.get('x-cache-tags')); await storeQueryCacheTags(queryId, cacheTags); }
return data;}If your deployment runs on many server instances, consider 'use cache: remote'. It stores the entries in a cache that all the instances share.
On pages with dynamic params, such as app/posts/[slug]/page.tsx, return the known params from generateStaticParams(), and export ensureStatic:
// Wait for the complete page after an invalidation, instead of serving an older prerenderexport const ensureStatic = 'navigation';Without it, when the page has no fresh cached render, Next.js can answer with an older prerendered version while it renders the new one. In our tests with next start, that older version was the one from the last build. On Vercel, we didn't see this. ensureStatic = 'navigation' also makes the build fail when the page reads uncached data, so the page can't become dynamic by accident.
Without Cache Components
Use the Next.js 15 code, with one change in the webhook: call revalidateTag(queryId, { expire: 0 }). Our Next.js Cache Tags starter uses this setup.
The webhook
import { revalidateTag } from 'next/cache';import type { CacheTag } from '@/lib/cache-tags';import { deleteQueries, queriesReferencingCacheTags } from '@/lib/database';
export async function POST(request: Request) { // Ensure that the request comes from the DatoCMS webhook if (request.headers.get('Webhook-Token') !== process.env.WEBHOOK_TOKEN) { return new Response('Invalid token', { status: 401 }); }
const { entity } = await request.json(); const cacheTags: CacheTag[] = entity.attributes.tags;
const queryIds = await queriesReferencingCacheTags(cacheTags);
// Forget the old tags: the next execution of each query stores its current ones await deleteQueries(queryIds);
for (const queryId of queryIds) { // Expire immediately, so the next visitor gets the new content revalidateTag(queryId, { expire: 0 }); }
return Response.json({ cacheTags, queryIds });}In the DatoCMS webhook settings, add a Webhook-Token header with the value of your WEBHOOK_TOKEN environment variable.
Next.js 15
We plan to move this section to a separate page. For new projects, use Next.js 16.
Tag each fetch() call with its Query ID, through the next.tags option:
import { createHash } from 'node:crypto';import { rawExecuteQuery } from '@datocms/cda-client';import type { TadaDocumentNode } from 'gql.tada';import { print } from 'graphql';import { parseXCacheTagsResponseHeader } from './cache-tags';import { storeQueryCacheTags } from './database';
export async function executeQuery<Result, Variables>( query: TadaDocumentNode<Result, Variables>, variables?: Variables,): Promise<Result> { const queryId = createHash('sha1') .update(print(query)) .update(JSON.stringify(variables) || '') .digest('hex');
const [data, response] = await rawExecuteQuery(query, { token: process.env.DATOCMS_API_TOKEN!, variables, returnCacheTags: true, requestInitOptions: { cache: 'force-cache', // One tag per query, whatever the number of DatoCMS Cache Tags next: { tags: [queryId] }, }, });
const cacheTags = parseXCacheTagsResponseHeader(response.headers.get('x-cache-tags')); await storeQueryCacheTags(queryId, cacheTags);
return data;}In each route that uses executeQuery(), set export const dynamic = 'force-static' as Route Segment Config, so that Next.js pre-renders the page and caches it.
The webhook is the same as on Next.js 16, except for one line: call revalidateTag(queryId), with one argument.
Rate limits on Vercel
Vercel limits the revalidation calls of each team: for example, 50 calls per second on the Hobby plan. The webhook calls revalidateTag() once per affected query. A publish that affects hundreds of queries can go over the limit, and Vercel then refuses the call with a 429. Check this if some pages don't update after big publishes.
The full example
We have prepared a Next.js project perfectly configured to integrate with DatoCMS Cache Tags. It uses Next.js 16 without Cache Components. Every part of the code is thoroughly commented to assist you in understanding.
We recommend starting from the "Useful resources to navigate the code" section of the README for a general overview, and links to the most important parts of the code in the repo.