cacheTag
Learn how to use the cacheTag function to manage cache invalidation in your Next.js application.
The cacheTag
function allows you to tag cached data for on-demand invalidation. By associating tags with cache entries, you can selectively purge or revalidate specific cache entries without affecting other cached data.
Usage
To use cacheTag
, enable the dynamicIO
flag in your next.config.js
file:
The cacheTag
function takes a single string value, or a string array.
You can then purge the cache on-demand using revalidateTag
API in another function, for example, a route handler or Server Action:
Good to know
- Idempotent Tags: Applying the same tag multiple times has no additional effect.
- Multiple Tags: You can assign multiple tags to a single cache entry by passing an array to
cacheTag
.
Examples
Tagging components or functions
Tag your cached data by calling cacheTag
within a cached function or component:
Creating tags from external data
You can use the data returned from an async function to tag the cache entry.
Invalidating tagged cache
Using revalidateTag
, you can invalidate the cache for a specific tag when needed: