revalidatePath
revalidatePath
允許您針對特定路徑按需清除 快取資料。
須知事項:
revalidatePath
可在 Node.js 和 Edge 運行環境 中使用。revalidatePath
僅會在下次訪問包含的路徑時使快取失效。這意味著使用動態路由區段呼叫revalidatePath
不會立即觸發大量重新驗證,失效只會在下次訪問該路徑時發生。
參數
revalidatePath(path: string, type?: 'page' | 'layout'): void;
path
: 可以是字串形式,表示您想重新驗證的資料所關聯的檔案系統路徑(例如/product/[slug]/page
),或是字面路由區段(例如/product/123
)。長度必須少於 1024 個字元。type
: (選填) 字串'page'
或'layout'
,用於變更要重新驗證的路徑類型。
返回值
revalidatePath
不返回任何值。
範例
重新驗證特定 URL
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/post-1')
這將在下次頁面訪問時重新驗證一個特定的 URL。
重新驗證頁面路徑
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'page')
// 或使用路由群組
revalidatePath('/(main)/post/[slug]', 'page')
這將在下次頁面訪問時重新驗證任何符合提供的 page
檔案的 URL。這 不會 使特定頁面下的頁面失效。例如,/blog/[slug]
不會使 /blog/[slug]/[author]
失效。
重新驗證佈局路徑
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'layout')
// 或使用路由群組
revalidatePath('/(main)/post/[slug]', 'layout')
這將在下次頁面訪問時重新驗證任何符合提供的 layout
檔案的 URL。這會導致具有相同佈局的子頁面在下次訪問時重新驗證。例如,在上述情況下,/blog/[slug]/[another]
也會在下次訪問時重新驗證。
伺服器動作 (Server Action)
'use server'
import { revalidatePath } from 'next/cache'
export default async function submit() {
await submitForm()
revalidatePath('/')
}
路由處理器 (Route Handler)
import { revalidatePath } from 'next/cache'
import { 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',
})
}
import { revalidatePath } from 'next/cache'
export async function GET(request) {
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',
})
}