cacheTag
Last updated October 22, 2025
ThecacheTag 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 usecacheTag, enable thecacheComponents flag in yournext.config.js file:
next.config.ts
importtype { NextConfig }from'next'constnextConfig:NextConfig= { cacheComponents:true,}exportdefault nextConfigThecacheTag function takes one or more string values.
app/data.ts
import { cacheTag }from'next/cache'exportasyncfunctiongetData() {'use cache'cacheTag('my-data')constdata=awaitfetch('/api/data')return data}You can then purge the cache on-demand usingrevalidateTag API in another function, for example, aroute handler orServer Action:
app/action.ts
'use server'import { revalidateTag }from'next/cache'exportdefaultasyncfunctionsubmit() {awaitaddPost()revalidateTag('my-data')}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 multiple string values to
cacheTag.
cacheTag('tag-one','tag-two')- Limits: The max length for a custom tag is 256 characters and the max tag items is 128.
Examples
Tagging components or functions
Tag your cached data by callingcacheTag within a cached function or component:
app/components/bookings.tsx
import { cacheTag }from'next/cache'interfaceBookingsProps { type:string}exportasyncfunctionBookings({ type='haircut' }:BookingsProps) {'use cache'cacheTag('bookings-data')asyncfunctiongetBookingsData() {constdata=awaitfetch(`/api/bookings?type=${encodeURIComponent(type)}`)return data }return//...}Creating tags from external data
You can use the data returned from an async function to tag the cache entry.
app/components/bookings.tsx
import { cacheTag }from'next/cache'interfaceBookingsProps { type:string}exportasyncfunctionBookings({ type='haircut' }:BookingsProps) {asyncfunctiongetBookingsData() {'use cache'constdata=awaitfetch(`/api/bookings?type=${encodeURIComponent(type)}`)cacheTag('bookings-data',data.id)return data }return//...}Invalidating tagged cache
UsingrevalidateTag, you can invalidate the cache for a specific tag when needed:
app/actions.ts
'use server'import { revalidateTag }from'next/cache'exportasyncfunctionupdateBookings() {awaitupdateBookingData()revalidateTag('bookings-data')}Related
View related API references.
cacheComponents
Learn how to enable the cacheComponents flag in Next.js.
use cache
Learn how to use the use cache directive to cache data in your Next.js application.
revalidateTag
API Reference for the revalidateTag function.
cacheLife
Learn how to use the cacheLife function to set the cache expiration time for a cached function or component.
Was this helpful?