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

Next.js _middleware获取i18n locales返回undefined的解决方法

问题背景

我创建了i18n.json国际化配置文件,配置内容如下:

{
  "locales": ["en-US", "tr-TR"],
  "defaultLocale": "tr-TR",
  "defaultNS": "common",
  "pages": {
    "*": ["common"]
  }
}

需求是在_middleware.tsx中获取配置的可用locales数组["en-US", "tr-TR"]。参照Next.js官方文档中nextUrl包含i18n属性的说明,尝试通过如下代码读取i18n对象中的locales字段,但实际得到undefined值:

import { NextResponse, NextRequest } from "next/server";
    
export async function middleware(req: NextRequest) {
  const { i18n } = req.nextUrl;
  const { locales } = i18n;

  console.log(locales);

  return NextResponse.next();
}
问题原因

req.nextUrl.i18n 是Next.js内置i18n路由能力提供的注入属性,只有当你在next.config.js中声明了i18n相关配置时,该字段才会被正确赋值。你当前将i18n配置单独存放在i18n.json文件中(通常是next-i18next这类第三方国际化库的配置方式),Next.js本身不会自动读取该文件内容注入到请求对象,因此读取结果为undefined。

解决方案

根据你使用的国际化方案二选一即可:

  • 方案1:使用Next.js内置i18n路由
    将locales、defaultLocale等i18n核心配置迁移到next.config.js中,配置示例:
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      i18n: {
        locales: ["en-US", "tr-TR"],
        defaultLocale: "tr-TR",
      }
    }
    
    module.exports = nextConfig
    
    配置完成后重启开发服务,原代码中req.nextUrl.i18n.locales即可正常读取到配置的语言列表。
  • 方案2:使用第三方i18n库(如next-i18next)
    不需要依赖请求对象的注入字段,直接在middleware中引入你编写的i18n配置文件读取对应值即可,示例代码:
    import { NextResponse, NextRequest } from "next/server";
    // 注意根据你的i18n.json实际存放路径调整引入路径
    import i18nConfig from "./i18n.json";
    
    export async function middleware(req: NextRequest) {
      const { locales } = i18nConfig;
      console.log(locales); // 正常输出 ["en-US", "tr-TR"]
      return NextResponse.next();
    }
    
    如果你的配置是写在next-i18next.config.js中,操作逻辑完全一致,引入对应文件读取locales字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 06:15:40