Menu

How to implement Incremental Static Regeneration (ISR)

示例

增量静态再生(ISR)使你能够:

  • 更新静态内容而无需重新构建整个站点
  • 通过为大多数请求提供预渲染的静态页面来减少服务器负载
  • 确保自动为页面添加正确的 cache-control
  • 处理大量内容页面而无需较长的 next build 时间

这是一个最小示例:

pages/blog/[id].tsx
TypeScript
import type { GetStaticPaths, GetStaticProps } from 'next'
 
interface Post {
  id: string
  title: string
  content: string
}
 
interface Props {
  post: Post
}
 
export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await fetch('https://api.vercel.app/blog').then((res) =>
    res.json()
  )
  const paths = posts.map((post: Post) => ({
    params: { id: String(post.id) },
  }))
 
  return { paths, fallback: 'blocking' }
}
 
export const getStaticProps: GetStaticProps<Props> = async ({
  params,
}: {
  params: { id: string }
}) => {
  const post = await fetch(`https://api.vercel.app/blog/${params.id}`).then(
    (res) => res.json()
  )
 
  return {
    props: { post },
    // 当请求到来时,Next.js 将使缓存失效,
    // 最多每 60 秒一次。
    revalidate: 60,
  }
}
 
export default function Page({ post }: Props) {
  return (
    <main>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </main>
  )
}

这个示例的工作原理如下:

  1. next build 期间,所有已知的博客文章都会被生成
  2. 对这些页面的所有请求(例如 /blog/1)都会被缓存并且是即时的
  3. 60 秒过后,下一个请求仍然会返回缓存的(现在已过时的)页面
  4. 缓存失效,新版本的页面开始在后台生成
  5. 成功生成后,下一个请求将返回更新后的页面,并为后续请求缓存它
  6. 如果请求 /blog/26,并且它存在,该页面将按需生成。可以通过使用不同的 fallback 值来更改此行为。但是,如果该文章不存在,则返回 404。

参考

函数

示例

使用 res.revalidate() 进行按需验证

为了获得更精确的重新验证方法,请使用 res.revalidate 从 API Router 按需生成新页面。

例如,可以在 /api/revalidate?secret=<token> 处调用此 API Route 来重新验证给定的博客文章。创建一个仅你的 Next.js 应用知道的密钥令牌。此密钥将用于防止未经授权访问重新验证 API Route。

pages/api/revalidate.ts
TypeScript
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // 检查密钥以确认这是有效请求
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' })
  }
 
  try {
    // 这应该是实际路径而不是重写的路径
    // 例如,对于 "/posts/[id]",这应该是 "/posts/1"
    await res.revalidate('/posts/1')
    return res.json({ revalidated: true })
  } catch (err) {
    // 如果出现错误,Next.js 将继续
    // 显示最后成功生成的页面
    return res.status(500).send('Error revalidating')
  }
}

如果你使用按需重新验证,则无需在 getStaticProps 中指定 revalidate 时间。Next.js 将使用默认值 false(无重新验证),并且仅在调用 res.revalidate() 时按需重新验证页面。

处理未捕获的异常

如果在处理后台再生时 getStaticProps 内部出现错误,或者你手动抛出错误,最后成功生成的页面将继续显示。在下一个后续请求中,Next.js 将重试调用 getStaticProps

pages/blog/[id].tsx
TypeScript
import type { GetStaticProps } from 'next'
 
interface Post {
  id: string
  title: string
  content: string
}
 
interface Props {
  post: Post
}
 
export const getStaticProps: GetStaticProps<Props> = async ({
  params,
}: {
  params: { id: string }
}) => {
  // 如果此请求抛出未捕获的错误,Next.js 将不会
  // 使当前显示的页面失效,并在下一个请求时
  // 重试 getStaticProps。
  const res = await fetch(`https://api.vercel.app/blog/${params.id}`)
  const post: Post = await res.json()
 
  if (!res.ok) {
    // 如果出现服务器错误,你可能希望
    // 抛出错误而不是返回,以便在下一次成功请求之前
    // 缓存不会更新。
    throw new Error(`Failed to fetch posts, received status ${res.status}`)
  }
 
  return {
    props: { post },
    // 当请求到来时,Next.js 将使缓存失效,
    // 最多每 60 秒一次。
    revalidate: 60,
  }
}

自定义缓存位置

如果你想将缓存的页面和数据持久化到持久存储,或在 Next.js 应用程序的多个容器或实例之间共享缓存,可以配置 Next.js 缓存位置。了解更多

故障排除

在本地开发中调试缓存数据

如果你使用 fetch API,可以添加额外的日志记录来了解哪些请求被缓存或未被缓存。了解更多关于 logging 选项的信息

next.config.js
module.exports = {
  logging: {
    fetches: {
      fullUrl: true,
    },
  },
}

验证正确的生产行为

要验证你的页面在生产环境中是否正确缓存和重新验证,你可以通过运行 next build 然后运行 next start 来本地测试以运行生产 Next.js 服务器。

这将允许你测试 ISR 行为,就像它在生产环境中工作一样。为了进一步调试,将以下环境变量添加到你的 .env 文件:

.env
NEXT_PRIVATE_DEBUG_CACHE=1

这将使 Next.js 服务器控制台记录 ISR 缓存命中和未命中。你可以检查输出以查看在 next build 期间生成了哪些页面,以及按需访问路径时如何更新页面。

注意事项

  • ISR 仅在使用 Node.js 运行时(默认)时受支持。
  • 创建静态导出时不支持 ISR。
  • 代理不会对按需 ISR 请求执行,这意味着代理中的任何路径重写或逻辑都不会被应用。确保你正在重新验证确切的路径。例如,/post/1 而不是重写的 /post-1

平台支持

部署选项支持情况
Node.js 服务器
Docker 容器
静态导出
适配器取决于平台

了解如何在自托管 Next.js 时配置 ISR

版本历史

版本变更
v14.1.0自定义 cacheHandler 稳定。
v13.0.0引入 App Router。
v12.2.0Pages Router:按需 ISR 稳定
v12.0.0Pages Router:添加 Bot-aware ISR fallback
v9.5.0Pages Router:引入稳定的 ISR