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

基于Strapi CMS与Next.js实现404状态码及错误页跳转

解决方案:Next.js + Strapi 实现404错误页与状态码返回

问题分析

你当前的代码存在以下核心问题:

  • 仅渲染了Strapi中的错误页内容,但未触发Next.js的404响应机制,导致浏览器返回200状态码而非404
  • 中间件中尝试通过修改headers设置状态码的方式无效,Next.js的响应状态需通过页面路由逻辑显式声明
  • 组件层的错误标识未对响应状态产生实际影响

以下分App Router(Next.js 13+)和Pages Router两种场景给出标准实现方案:


方案一:App Router(app目录结构)

1. 修改动态路由页面(app/[lang]/[slug]/page.tsx)

通过notFound()函数触发Next.js的404响应,同时自动渲染全局或路由级的error.tsx组件:

import { notFound } from 'next/navigation';

type Props = {
  params: { lang: string; slug: string };
};

export default async function PageRoute({ params }: Props) {
  const page = await getPageBySlug(params.slug, params.lang);

  // 校验Strapi返回的页面数据有效性
  if (!page || !page.data || page.data.length === 0) {
    // 触发404状态,Next.js将渲染error.tsx
    notFound();
  }

  const contentSections = page.data[0].attributes.contentSections;
  return contentSections.map((section: any, index: number) => sectionRenderer(section, index));
}

2. 创建路由级错误组件(app/[lang]/error.tsx)

在错误组件中获取对应语言的Strapi错误页数据,确保显示自定义错误内容:

'use client';
import { useParams } from 'next/navigation';
import useSWR from 'swr';

// 数据获取工具函数
const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error('Failed to fetch error page');
  return res.json();
};

export default function ErrorPage() {
  const params = useParams();
  const lang = params.lang as string;

  // 获取对应语言的错误页数据
  const { data: errorPage, error } = useSWR(
    `/api/get-page?slug=error&lang=${lang}`,
    fetcher
  );

  if (error || !errorPage) {
    return <div>Page Not Found</div>;
  }

  const contentSections = errorPage.data[0].attributes.contentSections;
  return contentSections.map((section: any, index: number) => sectionRenderer(section, index));
}

方案二:Pages Router(pages目录结构)

通过getServerSideProps返回notFound: true来设置404状态码,同时传递Strapi错误页数据给页面组件:

type Props = {
  page: any;
};

export default function PageRoute({ page }: Props) {
  const contentSections = page.data[0].attributes.contentSections;
  return contentSections.map((section: any, index: number) => sectionRenderer(section, index));
}

export async function getServerSideProps(context: any) {
  const { params } = context;
  const page = await getPageBySlug(params.slug, params.lang);

  if (!page || !page.data || page.data.length === 0) {
    // 获取对应语言的错误页数据
    const errorPage = await getPageBySlug('error', params.lang);
    
    // 返回404状态码和错误页数据
    return {
      props: { page: errorPage },
      notFound: true,
    };
  }

  return {
    props: { page },
  };
}

关键注意事项

  • 确保getPageBySlug函数能正确处理请求失败的情况,返回格式统一的空数据(而非抛出未捕获错误)
  • 若使用静态生成(getStaticProps),需设置fallback: true或fallback: 'blocking',并在getStaticProps中执行相同的空数据校验与notFound返回
  • 浏览器网络控制台将自动显示404状态码,无需手动设置headers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 15:27:34