You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Next.js的静态路由开启带fallback的ISR增量静态再生功能

可以实现。getStaticPaths确实仅对[slug].jsx这类动态路由生效,静态路由可通过以下方案实现构建时不预生成、首次访问触发生成的带fallback的ISR效果:

Pages Router 适配方案

方案1:路由重写映射到动态路由

无需修改现有页面逻辑,通过路由规则让静态路由复用动态路由的ISR能力:

  1. 在pages目录下创建动态路由文件[root].jsx,编写原index.jsx的页面逻辑,导出配置如下:
export const getStaticPaths = () => {
  return {
    paths: [],
    fallback: 'blocking'
  }
}

export const getStaticProps = async (ctx) => {
  // 仅匹配根路径请求,其他路径返回404
  if (ctx.params.root !== undefined) {
    return { notFound: true }
  }
  // 你的页面数据获取逻辑
  const pageData = await fetch('你的数据源接口').then(res => res.json())
  return {
    props: { pageData },
    revalidate: 60 // 按需求设置缓存刷新周期,单位秒
  }
}
  1. 在项目根目录的next.config.js中添加重写规则:
module.exports = {
  async rewrites() {
    return [
      { source: '/', destination: '/[root]' }
    ]
  }
}

方案2:直接跳过构建期生成(Next.js 12.2+ 支持)

不需要调整路由结构,直接在原index.jsx的getStaticProps中添加跳过构建的配置即可:

export const getStaticProps = async () => {
  // 构建阶段直接跳过页面生成
  if (process.env.NEXT_PHASE === 'phase-production-build') {
    return {
      // Next.js 12.2 ~ 13.3 用unstable_skipGeneration,13.4+ 改名为excludeFromBuild
      excludeFromBuild: true,
      revalidate: 60
    }
  }

  // 运行时页面数据获取逻辑
  const pageData = await fetch('你的数据源接口').then(res => res.json())
  return {
    props: { pageData },
    revalidate: 60
  }
}

该配置的效果和fallback: 'blocking'的ISR完全一致:首次访问时服务端阻塞生成页面后返回,后续访问直接命中缓存,到达revalidate设定的时间后自动后台刷新缓存。

App Router 适配方案

Next.js 13+ App Router下实现更简单,直接在根页面app/page.jsx添加如下配置即可:

// 开启ISR缓存,设置缓存有效期
export const revalidate = 60
// 禁止构建期预生成页面
export const generateStaticParams = () => []

内容的提问来源于stack exchange,提问作者BlackGlory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:18:03