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

Next.js 14:middleware.js无法从嵌套路由获取正确pathname

解决Next.js 14 Middleware无法获取完整嵌套路由pathname的问题

问题分析

访问/en/products时,Middleware中request.nextUrl.pathname仅返回/en而非预期的/en/products,核心原因可能是:

  • Middleware未匹配到完整嵌套路由路径,导致仅在根路由段触发
  • 手动解析locale的逻辑干扰了路径获取,或未正确利用Next.js官方的国际化路由能力

解决方案

1. 配置Middleware匹配所有路径

在middleware.js顶部添加matcher配置,确保Middleware对所有非静态资源、非API路径生效:

export const matcher = [
  '/((?!api|_next/static|_next/image|favicon.ico).*)',
];

export function middleware(request) {
  // 你的逻辑代码
}

2. 利用Next.js官方国际化路由的locale属性(推荐)

如果遵循官方国际化文档配置了next.config.js的i18n选项,直接使用request.nextUrl.locale获取当前locale,无需手动解析路径:

// 假设next.config.js已配置i18n
export function middleware(request) {
  const { pathname, locale } = request.nextUrl;
  console.log(pathname); // 此时会输出完整路径如/en/products

  if(currentRole === ROLES.ADMIN) {
    if(!pathname.startsWith(`/${locale}/customer`)) {
      if(locale !== 'en') {
        request.nextUrl.pathname = '/en';
        return NextResponse.redirect(request.nextUrl);
      }
    }
  }
}

3. 检查next.config.js的国际化配置

确保next.config.js中的i18n配置正确,示例:

/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ['en', 'zh'], // 你的语言列表
    defaultLocale: 'en',
    localeDetection: false, // 关闭自动检测,避免干扰自定义逻辑
  },
};

module.exports = nextConfig;

4. 验证目录结构与路由匹配

确认app/[lang]/products/page.js存在,确保Next.js能正确解析/en/products路由为该组件,避免因路由不存在导致的自动重定向。

额外注意事项

  • 清除浏览器缓存或使用无痕模式测试,避免旧路由缓存干扰结果
  • 检查是否有其他Middleware或路由重写规则修改了pathname值

内容的提问来源于stack exchange,提问作者M. Mudassar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:57:39