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

Next.js 12.3.1动态路由一段时间后随机跳转404问题求助

问题:Next.js 12.3.1动态路由偶发404(特定路由,运行1-2周后出现)
  • 部分动态路由初始运行正常,但随机运行1-2周后会意外跳转到404页面,仅特定路由出现此问题
  • API服务运行完全正常,无任何异常

相关代码

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const paramSlug = Array.isArray(params?.slug)
    ? params?.slug && params?.slug.length > 0
      ? params?.slug?.join('/')
      : ''
    : params?.slug;

  try {
    if (!paramSlug) {
      throw new Error('Not found!');
    }

    const api = new Api();
    const { body }: { body: any } = await api.get(paramSlug);
    const payload = body?.payload as IResourcePage;
    // if body is null then throw error
    if (!payload) {
      throw new Error(body.message);
    }
    const seo = (body?.seo_data || null) as string | null;

    return {
      props: {
        seo,
        pageData: payload || null,
      },
    };
  } catch (error: any) {
    return {
      notFound: true,
    };
  }
};

诊断与解决思路

1. 排查路由参数处理逻辑

  • 当前paramSlug的处理存在边界漏洞:若params.slug是长度为0的数组,会返回空字符串触发404。这种偶发情况,可能是前端路由跳转时参数拼接偶发错误,或CDN/缓存层篡改了路由参数
  • 建议添加请求日志,记录每次请求的params和paramSlug值,出现404时回溯日志确认参数是否符合预期

2. 优化API响应的异常处理

  • 代码中当!payload时直接取body.message,但如果body本身为null/undefined,会触发新的错误进入catch返回404,掩盖真实问题
  • 优化判断逻辑,先确认body存在,再处理payload,同时区分API请求异常(如超时、断连)与业务错误:
const { body }: { body: any } = await api.get(paramSlug);
// 先判断body是否存在
if (!body) {
  throw new Error('API响应为空');
}
const payload = body?.payload as IResourcePage;
if (!payload) {
  throw new Error(body.message || '无有效业务数据返回');
}

3. 检查缓存与路由配置

  • 虽然使用getServerSideProps默认无缓存,但部署平台(如Vercel、Netlify)的CDN缓存规则可能导致路由匹配异常,旧路由规则残留
  • 检查部署平台的缓存策略,确保动态路由请求不被缓存;同时确认[...slug].tsx这类路由文件是否有变更后未生效的情况

4. 排查API客户端与服务器稳定性

  • 检查Api类的实现,是否存在连接池耗尽、内存泄漏等问题,运行1-2周后导致API请求失败,进而触发404
  • 监控服务器资源使用(内存、CPU),确认是否存在长期运行后的资源耗尽情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:52:52