主题
revalidateTag
revalidateTag 允许你根据特定缓存标签按需使 缓存数据 失效。
¥revalidateTag allows you to invalidate cached data on-demand for a specific cache tag.
此功能非常适合允许轻微更新延迟的内容,例如博客文章、产品目录或文档。用户会收到过时的内容,同时后台会加载新数据。
¥This function is ideal for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. Users receive stale content while fresh data loads in the background.
用法
¥Usage
revalidateTag 可以在服务器函数和路由处理程序中调用。
¥revalidateTag can be called in Server Functions and Route Handlers.
revalidateTag 不能在客户端组件或代理中调用,因为它仅在服务器环境中有效。
¥revalidateTag cannot be called in Client Components or Proxy, as it only works in server environments.
重新验证行为
¥Revalidation Behavior
重新验证的行为取决于你是否提供了第二个参数:
¥The revalidation behavior depends on whether you provide the second argument:
使用
profile="max"(推荐):该标签条目被标记为过期,下次访问带有该标签的资源时,将使用“过期但重新验证”语义。这意味着在后台获取新内容的同时,会先提供过时的内容。¥With
profile="max"(recommended): The tag entry is marked as stale, and the next time a resource with that tag is visited, it will use stale-while-revalidate semantics. This means the stale content is served while fresh content is fetched in the background.通过自定义缓存生命周期配置文件:对于高级用法,你可以指定应用定义的任何缓存生命周期配置文件,从而实现根据你的特定缓存需求定制的自定义重新验证行为。
¥With a custom cache life profile: For advanced usage, you can specify any cache life profile that your application has defined, allowing for custom revalidation behaviors tailored to your specific caching requirements.
不使用第二个参数(已弃用):标签条目会立即过期,对该资源的下一个请求将导致阻塞式重新验证/缓存未命中。此行为现已弃用,你应该使用
profile="max"或迁移到updateTag。¥Without the second argument (deprecated): The tag entry is expired immediately, and the next request to that resource will be a blocking revalidate/cache miss. This behavior is now deprecated, and you should either use
profile="max"or migrate toupdateTag.
需要了解:使用
profile="max"时,revalidateTag会将标记的数据标记为过期,但只有在下次访问使用该标记的页面时才会获取新数据。这意味着调用revalidateTag不会立即触发多次重新验证。仅当下次访问使用该标签的任何页面时,才会发生失效。¥Good to know: When using
profile="max",revalidateTagmarks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means callingrevalidateTagwill not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag is next visited.
参数
¥Parameters
ts
revalidateTag(tag: string, profile: string | { expire?: number }): void;tag:表示与要重新验证的数据关联的缓存标记的字符串。不得超过 256 个字符。此值区分大小写。¥
tag: A string representing the cache tag associated with the data you want to revalidate. Must not exceed 256 characters. This value is case-sensitive.profile:指定重新验证行为的字符串。推荐值是"max",它提供“过期后重新验证”语义,或者cacheLife中定义的任何其他默认或自定义配置文件。或者,你可以传递一个带有expire属性的对象,以实现自定义过期行为。¥
profile: A string that specifies the revalidation behavior. The recommended value is"max"which provides stale-while-revalidate semantics, or any of the other default or custom profiles defined incacheLife. Alternatively, you can pass an object with anexpireproperty for custom expiration behavior.
必须先将标签分配给缓存数据。你可以通过两种方式实现:
¥Tags must first be assigned to cached data. You can do this in two ways:
将
next.tags选项与fetch结合使用以缓存外部 API 请求:¥Using the
next.tagsoption withfetchfor caching external API requests:
tsx
fetch(url, { next: { tags: ['posts'] } })在缓存函数或带有
'use cache'指令的组件中使用cacheTag:¥Using
cacheTaginside cached functions or components with the'use cache'directive:
tsx
import { cacheTag } from 'next/cache'
async function getData() {
'use cache'
cacheTag('posts')
// ...
}需要了解:单参数形式的
revalidateTag(tag)已弃用。目前,如果 TypeScript 错误被抑制,它也能正常工作,但此行为可能会在未来的版本中移除。更新为双参数签名。¥Good to know: The single-argument form
revalidateTag(tag)is deprecated. It currently works if TypeScript errors are suppressed, but this behavior may be removed in a future version. Update to the two-argument signature.
返回
¥Returns
revalidateTag 不返回值。
¥revalidateTag does not return a value.
与 revalidatePath 的关系
¥Relationship with revalidatePath
revalidateTag 会使所有使用特定标签的页面中的数据失效,而 revalidatePath 会使特定页面或布局路径失效。
¥revalidateTag invalidates data with specific tags across all pages that use those tags, while revalidatePath invalidates specific page or layout paths.
需要了解:这些函数用途不同,可能需要一起使用才能实现全面的数据一致性。有关详细示例和注意事项,请参阅 与 revalidateTag 和 updateTag 的关系 文档。
¥Good to know: These functions serve different purposes and may need to be used together for comprehensive data consistency. For detailed examples and considerations, see relationship with revalidateTag and updateTag for more information.
示例
¥Examples
以下示例演示了如何在不同的上下文中使用 revalidateTag。在这两种情况下,我们都使用 profile="max" 将数据标记为过期,并使用“过期但重新验证”语义,这是大多数用例的推荐方法。
¥The following examples demonstrate how to use revalidateTag in different contexts. In both cases, we're using profile="max" to mark data as stale and use stale-while-revalidate semantics, which is the recommended approach for most use cases.
服务器动作
¥Server Action
ts
'use server'
import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('posts', 'max')
}路由处理程序
¥Route Handler
ts
import type { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
if (tag) {
revalidateTag(tag, 'max')
return Response.json({ revalidated: true, now: Date.now() })
}
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing tag to revalidate',
})
}需要了解:对于需要立即过期的 Webhook 或第三方服务,你可以将
{ expire: 0 }作为第二个参数传递:revalidateTag(tag, { expire: 0 })。当外部系统调用你的路由处理程序并要求数据立即过期时,此模式是必要的。对于所有其他情况,建议在服务器操作中使用updateTag来进行即时更新。¥Good to know: For webhooks or third-party services that need immediate expiration, you can pass
{ expire: 0 }as the second argument:revalidateTag(tag, { expire: 0 }). This pattern is necessary when external systems call your Route Handlers and require data to expire immediately. For all other cases, it's recommended to useupdateTagin Server Actions for immediate updates instead.