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

Next.js 15 + next-intl使用headers()获取locale报错求助

Next.js 15 + next-intl 国际化布局中headers()已await仍报错问题

错误信息

Error: Route "/[locale]" used headers().get('X-NEXT-INTL-LOCALE'). headers() should be awaited before using its value.

布局代码

import { NextIntlClientProvider } from "next-intl";
import { headers } from "next/headers";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  return [{ locale: "en" }, { locale: "lt" }];
}

export default async function LocaleLayout({ children, params }) {
  const param = await params;
  const localeFromParams = param?.locale;

  const headerLocale = await headers().then((hdr) =>
    hdr.get("X-NEXT-INTL-LOCALE")
  );

  const locale = localeFromParams || headerLocale;

  if (!locale) {
    notFound();
  }

  let messages;
  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch (error) {
    notFound();
  }

  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider locale={locale} messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

已排查/尝试的操作

  • 已在布局中await params和headers(),但报错依旧
  • 确认middleware.js配置正常,next-intl可正确传递locale
  • 尝试在调用get('X-NEXT-INTL-LOCALE')前单独await headers(),问题未解决
  • 验证翻译文件导入路径正确
  • 分别尝试仅通过params.locale或headers().get(...)获取locale,均无效

翻译获取代码(request.js)

import { getRequestConfig } from "next-intl/server";

export default getRequestConfig(async ({ locale }) => {
  if (!locale) {
    console.error("Locale is undefined in getRequestConfig.");
    throw new Error("Locale is undefined in getRequestConfig.");
  }

  try {
    const messages = await import(`../messages/${locale}.json`);
    console.log("Loaded messages for locale:", locale);
    return { messages: messages.default };
  } catch (error) {
    console.error(`Failed to load messages for locale: ${locale}`, error);
    throw new Error(`Failed to load messages for locale: ${locale}`);
  }
});

疑问与预期

  • 为何已正确使用await仍出现该错误?
  • Next.js 15中使用next-intl是否有特定配置/模式需要遵循?
  • 预期:可从URL参数或请求头X-NEXT-INTL-LOCALE正确获取locale,并加载对应翻译文件

解决方案

1. 修正headers()的调用方式

在Next.js 15中,headers()本身是需要直接await的函数,你当前的写法await headers().then(...)逻辑上虽有等待,但语法上未正确awaitheaders()的返回值。修改为:

// 替换原headerLocale的获取代码
const hdr = await headers();
const headerLocale = hdr.get('X-NEXT-INTL-LOCALE');

2. 移除不必要的await params

App Router的布局组件中,params是直接传入的普通对象,无需await。直接使用params.locale即可:

// 替换原param相关代码
const localeFromParams = params?.locale;

3. 优化后的完整布局代码

import { NextIntlClientProvider } from "next-intl";
import { headers } from "next/headers";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  return [{ locale: "en" }, { locale: "lt" }];
}

export default async function LocaleLayout({ children, params }) {
  const localeFromParams = params?.locale;
  
  // 正确await headers()
  const hdr = await headers();
  const headerLocale = hdr.get('X-NEXT-INTL-LOCALE');

  const locale = localeFromParams || headerLocale;

  if (!locale) {
    notFound();
  }

  let messages;
  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch (error) {
    notFound();
  }

  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider locale={locale} messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

4. 额外注意事项

  • Next.js 15中,headers()、cookies()等属于Server Component专属函数,必须在async Server Component中使用,且必须直接await
  • 若使用next-intl官方路由方案,无需手动从headers获取locale——next-intl会通过middleware自动将locale注入到params中,直接依赖params.locale即可避免这类问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:29:54