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

Next.js 14使用next-intl实现国际化时遇上下文缺失错误求助

解决Next.js 14 + next-intl 「未找到NextIntlClientProvider上下文」错误

1. 确认根布局正确提供上下文

根布局(app/layout.tsx/jsx)是所有页面的入口,必须在这里用NextIntlClientProvider包裹子组件,并传入服务端获取的翻译消息:

// app/layout.tsx
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';

export default async function RootLayout({
  children,
  params: { locale }
}: {
  children: React.ReactNode;
  params: { locale: string };
}) {
  // 根据当前locale获取对应的翻译文件
  const messages = await getMessages({ locale });

  return (
    <html lang={locale}>
      <body>
        {/* 必须用NextIntlClientProvider包裹所有子内容 */}
        <NextIntlClientProvider messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

2. 验证中间件配置正确性

确保middleware.ts/js正确拦截路由并传递locale参数,示例配置:

// middleware.ts
import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
  // 配置你的支持语言列表
  locales: ['zh', 'en'],
  defaultLocale: 'zh'
});

// 匹配需要国际化的路由,排除API、静态资源等
export const config = {
  matcher: ['/', '/(zh|en)/:path*', '/((?!api|_next|_vercel|.*\\..*).*)']
};

3. 检查客户端组件的使用规范

  • 登录组件必须声明为客户端组件,开头加上'use client'指令;
  • 确保组件渲染在NextIntlClientProvider的上下文范围内(/app目录下默认所有页面都满足);
  • 禁止在服务端组件中调用useTranslations(该钩子仅支持客户端组件)。

客户端组件示例:

'use client';

import { useTranslations } from 'next-intl';

export default function LoginComponent() {
  const t = useTranslations('Login'); // 对应messages/{locale}/Login.json文件

  return (
    <div className="login-form">
      <h2>{t('title')}</h2>
      <input placeholder={t('emailPlaceholder')} type="email" />
      <input placeholder={t('passwordPlaceholder')} type="password" />
      <button>{t('submitBtn')}</button>
    </div>
  );
}

4. 验证翻译文件路径与格式

  • 翻译文件需放在messages/{locale}目录下,比如messages/zh/Login.json、messages/en/Login.json;
  • 文件格式为JSON键值对,示例:
// messages/zh/Login.json
{
  "title": "登录",
  "emailPlaceholder": "请输入邮箱",
  "passwordPlaceholder": "请输入密码",
  "submitBtn": "登录"
}

5. 检查版本兼容性

确保next-intl版本适配Next.js 14,建议安装最新稳定版:

npm install next-intl@latest

若以上步骤排查后仍未解决,可检查:

  • 是否存在嵌套布局未传递父上下文;
  • 是否有异步组件渲染时脱离了NextIntlClientProvider的包裹范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:33:14