Next.js 14中[lang]目录下not-found.tsx无法生效的问题求助
解决Next.js 14 App Router中[lang]目录下not-found.tsx不生效的问题
1. 检查Middleware的路由处理逻辑
确保你的Middleware没有错误拦截或重写未知路由,导致请求无法落到[lang]/not-found.tsx上。核心规则:
- 对未携带locale前缀的路径,重定向到带locale的版本(比如
/about→/en/about) - 对已携带locale前缀的未知路由(比如
/en/unknown-page),不要修改路径,让Next.js自动匹配对应的[lang]/not-found.tsx
示例Middleware代码参考:
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; const localeRegex = /^\/(en|zh-CN)\//; // 已带locale前缀的路径直接放行 if (localeRegex.test(pathname)) { return NextResponse.next(); } // 无locale前缀的路径重定向到默认locale版本 const defaultLocale = 'en'; return NextResponse.redirect(new URL(`/${defaultLocale}${pathname}`, request.url)); } export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], };
2. 确认[lang]目录的布局结构有效性
[lang]/not-found.tsx会继承所在目录的layout.tsx,需确保布局文件正确接收并传递locale参数,结构符合App Router要求:
// app/[lang]/layout.tsx export default function LangLayout({ children, params: { lang }, }: { children: React.ReactNode; params: { lang: string }; }) { return ( <html lang={lang}> <body>{children}</body> </html> ); }
3. 排查Next.js配置冲突
检查next.config.js,确保没有启用官方的i18n路由配置(自定义[lang]目录会与官方i18n逻辑冲突),同时避免任何自定义404相关配置:
// next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { // 移除或注释掉官方i18n配置 // i18n: { // locales: ['en', 'zh-CN'], // defaultLocale: 'en', // }, }; module.exports = nextConfig;
4. 确保not-found.tsx的导出规范
[lang]/not-found.tsx需正确导出默认组件,并可通过params获取locale:
// app/[lang]/not-found.tsx export default function NotFound({ params }: { params: { lang: string } }) { const errorMessage = params.lang === 'en' ? 'Page Not Found' : '页面未找到'; return ( <div style={{ padding: '2rem', textAlign: 'center' }}> <h1>404 - {errorMessage}</h1> </div> ); }
5. 清除缓存并重启服务
Next.js开发服务器的缓存可能导致路由匹配异常,执行以下操作:
- 停止开发服务器
- 删除项目根目录下的
.next文件夹 - 重新启动
npm run dev或yarn dev
6. 根目录not-found的兼容处理(可选)
如果仍有边缘场景触发根目录404,可在根目录添加not-found.tsx,通过重定向或获取locale后触发对应语言的404:
// app/not-found.tsx import { redirect } from 'next/navigation'; export default function RootNotFound() { // 从cookie或请求头获取用户偏好的locale(需在Middleware中提前写入) const locale = 'en'; // 替换为实际获取逻辑 redirect(`/${locale}/404`); }
内容的提问来源于stack exchange,提问作者Slobodan M.
相关产品推荐
相关产品推荐

