如何在NextJS App Router中实现多语言404页面?
Next.js 官方国际化方案解决 NotFound 组件无法获取语言参数问题
核心思路
将 not-found.tsx 放置到动态语言路由目录下(如 app/[lang]/),这样组件就能自动获取 URL 中的 lang 参数,无需依赖第三方库。
步骤1:调整目录结构
把根目录的 not-found.tsx 移动到 app/[lang]/ 目录下,目录结构如下:
app/ ├─ [lang]/ │ ├─ not-found.tsx │ └─ ...(其他页面组件) ├─ not-found.tsx(可选,处理根路径404) └─ ...
步骤2:修改 [lang]/not-found.tsx
让组件接收路由参数,并传递给 Error404:
import Error404 from "@/routes/Error404"; import { Locale } from "@root/i18n.config"; type Props = { params: { lang: Locale }; }; export default async function NotFound({ params }: Props) { return <Error404 lang={params.lang} />; }
步骤3:修改 Error404.tsx
接收 lang 参数并获取对应语言字典:
import { getDictionary } from "@/lib/dictionary"; import { Locale } from "@root/i18n.config"; import BigText from "@/components/BigText"; import Button from "@/components/Button"; import Heading from "@/components/Heading"; import Link from "next/link"; type Props = { lang: Locale; }; export default async function Error404({ lang }: Props) { const dict = await getDictionary(lang); return ( <div className="flex flex-1 flex-col justify-center items-center h-full"> <BigText text={dict.page.error[404].heading} /> <Heading text={dict.page.error[404].title} /> <Link href={`/${lang}`}> <Button text={dict.button.homePage} /> </Link> </div> ); }
步骤4:处理根路径404(可选)
若用户访问根目录下不存在的路径(如 /xxx),可在根目录 not-found.tsx 中重定向到默认语言或用户偏好语言的404页面:
import { redirect, headers } from "next/navigation"; import { locales, defaultLocale } from "@root/i18n.config"; export default async function RootNotFound() { // 从请求头获取用户偏好语言 const acceptLanguage = headers().get("accept-language"); let targetLang = defaultLocale; if (acceptLanguage) { const langList = acceptLanguage.split(",").map(item => item.split(";")[0]); for (const lang of langList) { if (locales.includes(lang as any)) { targetLang = lang as typeof defaultLocale; break; } } } redirect(`/${targetLang}/404`); }
关键配置确认
确保 next.config.js 中已配置国际化路由:
/** @type {import('next').NextConfig} */ const nextConfig = { i18n: { locales: ["en", "zh"], // 替换为你的语言列表 defaultLocale: "en", }, }; module.exports = nextConfig;
内容的提问来源于stack exchange,提问作者keir
相关产品推荐
相关产品推荐

