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

Next.js 14集成next-intl正常运行但控制台报错求助

解决Next.js 14 + next-intl控制台报错:Unable to find next-intl locale because the middleware didn't run on this request

报错根源

在服务器组件中调用useLocale()时,部分请求未经过next-intl的middleware处理,导致无法获取locale上下文。尽管功能正常,但特定场景(如直接刷新页面、静态生成触发)下会触发该报错。

解决方案

方案1:调整Middleware匹配规则,覆盖所有页面请求

修改middleware.ts的matcher配置,确保所有非Next.js内部路径的请求都经过middleware,注入locale上下文:

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

export default createMiddleware({
  locales: ['es', 'en'],
  defaultLocale: 'es'
});

export const config = {
  // 跳过Next.js内部资源、API路由和静态文件,匹配所有页面请求
  matcher: ['/((?!_next|api|favicon.ico).*)']
};

方案2:移除RootLayout中对useLocale()的依赖

原逻辑通过useLocale()校验params.locale的合法性,可直接通过支持的locale列表进行校验,避免依赖middleware注入的上下文:

// layout.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import "./globals.css";

// 定义支持的国际化语言列表
const supportedLocales = ['es', 'en'];

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { locale: string };
}) {
  // 直接校验当前路径的locale是否合法
  if (!supportedLocales.includes(params.locale)) {
    notFound();
  }

  return (
    <html lang={params.locale}>
      <body>{children}</body>
    </html>
  );
}

方案3:禁用Next.js内置国际化配置

若next.config.js中启用了Next.js原生i18n配置,会与next-intl冲突,导致middleware无法正常工作。需移除以下配置:

// next.config.js 中需删除的内容
module.exports = {
  i18n: {
    locales: ['es', 'en'],
    defaultLocale: 'es'
  }
};

验证方法

修改配置后重启Next.js开发服务器,刷新页面或直接访问带locale的路由,检查控制台是否仍存在报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:25:37