Skip to content

revalidatePath

revalidatePath 允许你根据特定路径按需使 缓存数据 失效。

¥revalidatePath allows you to invalidate cached data on-demand for a specific path.

用法

¥Usage

revalidatePath 可以在服务器函数和路由处理程序中调用。

¥revalidatePath can be called in Server Functions and Route Handlers.

revalidatePath 不能在客户端组件或中间件中调用,因为它只能在服务器环境中工作。

¥revalidatePath cannot be called in Client Components or Middleware, as it only works in server environments.

需要了解:

¥Good to know:

  • 服务器函数:立即更新 UI(如果查看重新验证的路径)。目前,它还会导致所有之前访问过的页面在再次导航时刷新。此行为是临时的,将来会更新以仅适用于特定路径。

    ¥Server Functions: Updates the UI immediately (if viewing the revalidated path). Currently, it also causes all previously visited pages to refresh when navigated to again. This behavior is temporary and will be updated in the future to apply only to the specific path.

  • 路由处理程序:标记需要重新验证的路径。重新验证在下次访问指定路径时进行。这意味着使用动态路由段调用 revalidatePath 不会立即触发多次重新验证。仅当下次访问该路径时才会发生失效。

    ¥Route Handlers: Marks the path for revalidation. The revalidation is done on the next visit to the specified path. This means calling revalidatePath with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.

参数

¥Parameters

tsx
revalidatePath(path: string, type?: 'page' | 'layout'): void;
  • path:表示与要重新验证的数据关联的文件系统路径的字符串(例如,/product/[slug]/page),或字面量路由段(例如,/product/123)。不得超过 1024 个字符。此值区分大小写。

    ¥path: Either a string representing the filesystem path associated with the data you want to revalidate (for example, /product/[slug]/page), or the literal route segment (for example, /product/123). Must not exceed 1024 characters. This value is case-sensitive.

  • type:(可选)'page''layout' 字符串更改要重新验证的路径类型。如果 path 包含动态段(例如 /product/[slug]/page),则需要此参数。如果路径指的是文字路由段,例如动态页面的 /product/1(例如 /product/[slug]/page),则不应提供 type

    ¥type: (optional) 'page' or 'layout' string to change the type of path to revalidate. If path contains a dynamic segment (for example, /product/[slug]/page), this parameter is required. If path refers to the literal route segment, e.g., /product/1 for a dynamic page (e.g., /product/[slug]/page), you should not provide type.

返回

¥Returns

revalidatePath 不返回值。

¥revalidatePath does not return a value.

哪些内容可以失效

¥What can be invalidated

path 参数可以指向页面、布局或路由处理程序:

¥The path parameter can point to pages, layouts, or route handlers:

  • 页面:使特定页面无效

    ¥Pages: Invalidates the specific page

  • 布局:使布局及其下的所有页面无效

    ¥Layouts: Invalidates the layout and all pages beneath it

  • 路由处理程序:使路由处理程序中访问的数据缓存条目无效。例如,revalidatePath("/api/data") 会使以下 GET 处理程序失效:

    ¥Route Handlers: Invalidates Data Cache entries accessed within route handlers. For example revalidatePath("/api/data") invalidates this GET handler:

ts
export async function GET() {
  const data = await fetch('https://api.vercel.app/blog', {
    cache: 'force-cache',
  })

  return Response.json(await data.json())
}

revalidateTag 的关系

¥Relationship with revalidateTag

revalidatePathrevalidateTag 有不同的用途:

¥revalidatePath and revalidateTag serve different purposes:

  • revalidatePath:使特定页面或布局路径无效

    ¥revalidatePath: Invalidates a specific page or layout path

  • revalidateTag:使所有使用这些标签的页面中带有特定标签的数据无效

    ¥revalidateTag: Invalidates data with specific tags across all pages that use those tags

调用 revalidatePath 时,只有指定路径会在下次访问时获取最新数据。使用相同数据标签的其他页面将继续提供缓存数据,直到这些特定标签也重新验证:

¥When you call revalidatePath, only the specified path gets fresh data on the next visit. Other pages that use the same data tags will continue to serve cached data until those specific tags are also revalidated:

tsx
// Page A: /blog
const posts = await fetch('https://api.vercel.app/blog', {
  next: { tags: ['posts'] },
})

// Page B: /dashboard
const recentPosts = await fetch('https://api.vercel.app/blog?limit=5', {
  next: { tags: ['posts'] },
})

调用 revalidatePath('/blog') 后:

¥After calling revalidatePath('/blog'):

  • 页面 A (/blog):显示最新数据(页面重新渲染)

    ¥Page A (/blog): Shows fresh data (page re-rendered)

  • 页面 B (/dashboard):仍然显示过时数据(缓存标签 'posts' 未失效)

    ¥Page B (/dashboard): Still shows stale data (cache tag 'posts' not invalidated)

构建重新验证实用程序

¥Building revalidation utilities

revalidatePathrevalidateTag 是互补的原语,通常在实用函数中一起使用,以确保整个应用的全面数据一致性:

¥revalidatePath and revalidateTag are complementary primitives that are often used together in utility functions to ensure comprehensive data consistency across your application:

ts
'use server'

import { revalidatePath, revalidateTag } from 'next/cache'

export async function updatePost() {
  await updatePostInDatabase()

  revalidatePath('/blog') // Refresh the blog page
  revalidateTag('posts') // Refresh all pages using 'posts' tag
}

此模式可确保特定页面和使用相同数据的任何其他页面保持一致。

¥This pattern ensures that both the specific page and any other pages using the same data remain consistent.

示例

¥Examples

重新验证特定 URL

¥Revalidating a specific URL

ts
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/post-1')

这将使一个特定的 URL 失效,以便在下次访问页面时重新验证。

¥This will invalidate one specific URL for revalidation on the next page visit.

重新验证页面路径

¥Revalidating a Page path

ts
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'page')
// or with route groups
revalidatePath('/(main)/blog/[slug]', 'page')

这将使任何与提供的 page 文件匹配的 URL 失效,以便在下次访问页面时重新验证。这不会使特定页面下方的页面失效。例如,/blog/[slug] 不会使 /blog/[slug]/[author] 无效。

¥This will invalidate any URL that matches the provided page file for revalidation on the next page visit. This will not invalidate pages beneath the specific page. For example, /blog/[slug] won't invalidate /blog/[slug]/[author].

重新验证布局路径

¥Revalidating a Layout path

ts
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'layout')
// or with route groups
revalidatePath('/(main)/post/[slug]', 'layout')

这将使任何与提供的 layout 文件匹配的 URL 失效,以便在下次访问页面时重新验证。这将导致具有相同布局的页面在下次访问时失效并重新验证。例如,在上述情况下,/blog/[slug]/[another] 也会失效,并在下次访问时重新验证。

¥This will invalidate any URL that matches the provided layout file for revalidation on the next page visit. This will cause pages beneath with the same layout to be invalidated and revalidated on the next visit. For example, in the above case, /blog/[slug]/[another] would also be invalidated and revalidated on the next visit.

重新验证所有数据

¥Revalidating all data

ts
import { revalidatePath } from 'next/cache'

revalidatePath('/', 'layout')

这将清除客户端路由缓存,并使数据缓存失效,以便在下次访问页面时重新验证。

¥This will purge the Client-side Router Cache, and invalidate the Data Cache for revalidation on the next page visit.

服务器功能

¥Server Function

ts
'use server'

import { revalidatePath } from 'next/cache'

export default async function submit() {
  await submitForm()
  revalidatePath('/')
}

路由处理程序

¥Route Handler

ts
import { revalidatePath } from 'next/cache'
import type { NextRequest } from 'next/server'

export async function GET(request: NextRequest) {
  const path = request.nextUrl.searchParams.get('path')

  if (path) {
    revalidatePath(path)
    return Response.json({ revalidated: true, now: Date.now() })
  }

  return Response.json({
    revalidated: false,
    now: Date.now(),
    message: 'Missing path to revalidate',
  })
}