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

Next.js14+App Router+i18NextJs下NotFound页面异常及标签缺失问题

解决Next.js 14 + App Router + next-i18n-router集成i18next的常见问题

问题概述

使用Next.js 14 App Router结合next-i18n-router集成i18next时,出现以下问题:

  • 自定义/默认NotFound页面失效
  • RootLayout组件提示缺失<html>/<body>标签
  • 服务端日志提示middleware.ts导出配置无法解析

依赖版本参考

  • next: 14.0.x
  • next-i18n-router: 5.x.x
  • i18next: 23.x.x
  • react-i18next: 13.x.x

1. 修复middleware.ts配置解析错误

next-i18n-router要求middleware必须导出正确的config匹配器和处理函数,示例代码如下:

import { i18nRouter } from 'next-i18n-router';
import { NextRequest } from 'next/server';

// 匹配所有非API、静态资源、Next.js内部路径
export const config = {
  matcher: '/((?!api|static|.*\\..*|_next).*)',
};

export function middleware(request: NextRequest) {
  return i18nRouter(request, {
    locales: ['en', 'zh'], // 替换为你的语言列表
    defaultLocale: 'en',
    prefixDefaultLocale: true, // 根据需求设置是否给默认语言加前缀
  });
}

排查点:

  • 确保config是小写导出,拼写无误
  • 检查matcher规则是否覆盖了所有需要国际化的路径
  • 确认next-i18n-router版本与Next.js 14兼容(v5+支持App Router)

2. 修复RootLayout标签缺失错误

App Router的RootLayout(app/layout.tsx)必须返回包裹<html>和<body>的结构,并通过路由参数获取locale设置语言属性:

import { ReactNode } from 'react';

export default function RootLayout({
  children,
  params: { locale },
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  return (
    <html lang={locale}>
      <body>{children}</body>
    </html>
  );
}

排查点:

  • 必须从params中接收locale参数(由next-i18n-router自动注入)
  • 确保结构最外层是<html>,内部包含<body>
  • RootLayout默认是服务端组件,无需添加'use client'指令(如需使用i18next客户端hooks,可在子layout中处理)

3. 修复NotFound页面失效问题

在国际化路由结构下,NotFound页面需放在[locale]路由组内,文件结构如下:

app/
  [locale]/
    not-found.tsx  // 对应各语言的404页面
    layout.tsx
    page.tsx
  layout.tsx

自定义NotFound页面示例(客户端组件,可使用i18next翻译):

'use client';
import { useTranslation } from 'react-i18next';

export default function NotFound() {
  const { t } = useTranslation();
  return (
    <div style={{ padding: '2rem' }}>
      <h1>{t('404.title')}</h1>
      <p>{t('404.description')}</p>
    </div>
  );
}

排查点:

  • 不要将NotFound页面放在根目录app/not-found.tsx(会被国际化路由拦截)
  • 确保middleware的matcher规则没有排除404路径
  • 子layout([locale]/layout.tsx)需正确传递children

额外配置检查

  1. next.config.js:无需额外i18n配置,但如果之前配置过,需与middleware中的locale列表一致:
/** @type {import('next').NextConfig} */
const nextConfig = {
  // 若已配置,需与middleware中的locales/defaultLocale匹配
  // i18n: {
  //   locales: ['en', 'zh'],
  //   defaultLocale: 'en',
  // },
};

module.exports = nextConfig;
  1. i18next初始化:在客户端组件入口(如[locale]/layout.tsx)初始化i18n:
'use client';
import '../../i18n'; // 导入你的i18n配置文件
import { ReactNode } from 'react';

export default function LocaleLayout({ children }: { children: ReactNode }) {
  return <>{children}</>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:05:57