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

如何在NextJS中间件中获取当前活跃Locale?

在Next.js中间件中获取活跃Locale的方法

当然可以在Next.js中间件中获取活跃Locale,无需依赖客户端的useRouter钩子,直接通过请求对象即可实现,具体操作如下:

核心实现方式(Next.js 13+ App Router)

在中间件中,NextRequest 对象的 nextUrl 属性已经内置了Locale相关信息,直接读取即可:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // 获取当前活跃Locale
  const activeLocale = request.nextUrl.locale;
  // 获取项目配置的默认Locale
  const defaultLocale = request.nextUrl.defaultLocale;

  // 示例:打印当前Locale
  console.log(`当前活跃Locale: ${activeLocale}`);
  console.log(`默认Locale: ${defaultLocale}`);

  // 后续业务逻辑,比如根据Locale做路由重定向、权限校验等
  if (activeLocale === 'zh') {
    // 针对中文Locale的特殊处理
  }

  return NextResponse.next();
}

关键注意事项

  • 确保项目已在 next.config.js 中正确配置国际化(i18n)规则,比如路径、域名映射等,nextUrl.locale 才能正确识别Locale
  • 无论你使用路径式国际化(如 /en/about、/zh/about)还是域名/子域名式国际化,request.nextUrl.locale 都能自动匹配配置返回对应Locale值
  • 中间件运行在服务端/边缘节点,无法使用客户端钩子(如useRouter),必须通过请求对象获取服务端可用的Locale信息

特殊场景处理(自定义路由规则)

如果你的项目使用了自定义路由规则,Next.js自动识别Locale失效的话,可以通过解析URL路径手动提取:

export function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;
  // 假设路径格式为 /[locale]/xxx
  const localeMatch = pathname.match(/^\/([a-z]{2})\/.*$/);
  const activeLocale = localeMatch ? localeMatch[1] : request.nextUrl.defaultLocale;

  console.log('手动提取的Locale:', activeLocale);
  return NextResponse.next();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:22:49