Next.js 14中如何链式调用Auth.js与多语言重定向中间件?
解决Next.js多语言中间件与Auth.js v5的函数名冲突问题
你可以通过将原有多语言逻辑封装为独立函数,再与Auth.js的中间件合并的方式解决冲突,具体步骤如下:
1. 调整导入与函数命名
将Auth.js的auth导入时重命名,避免与自定义中间件函数名冲突,同时导入你的多语言配置依赖:
import { auth as authMiddleware } from "@/lib/auth"; import { NextResponse } from "next/server"; import { locales, getLocale } from "@/lib/locales"; // 导入你的多语言配置和获取locale的方法
2. 封装多语言重定向逻辑
把原来的locale处理逻辑抽成独立函数,并将原matcher的跳过路径逻辑整合到函数内部:
function handleLocaleRedirect(request) { const pathname = request.nextUrl.pathname; // 跳过内部路径(与原matcher规则一致) const isExcludedPath = /^\/(api|assets|docs|_next)/.test(pathname) || /\..+$/.test(pathname); // 跳过带后缀的文件路径 if (isExcludedPath) return null; // 判断路径是否缺少locale标识 const pathnameMissingLocale = locales.every( (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}` ); if (pathnameMissingLocale) { const locale = getLocale(request); // 处理根路径的特殊情况,避免生成`//`的错误路径 const newPath = pathname === "/" ? `/${locale}` : `/${locale}${pathname}`; return NextResponse.redirect(new URL(newPath, request.url)); } // 无需重定向,返回null继续执行后续逻辑 return null; }
3. 合并中间件逻辑
创建最终的middleware函数,先执行多语言重定向,再调用Auth.js的中间件处理认证:
export async function middleware(request) { // 先处理locale重定向,若有重定向则直接返回结果 const localeResponse = handleLocaleRedirect(request); if (localeResponse) { return localeResponse; } // 若无重定向,交给Auth.js的中间件处理认证逻辑 return authMiddleware(request); } // 注意:不要导出config.matcher,符合Auth.js v5的要求
关键说明
- 执行顺序优先:必须先处理多语言重定向,再进行Auth认证,确保用户最终访问的是带locale的有效路径,避免Auth逻辑处理无locale的无效地址。
- 替代matcher规则:将原
config.matcher的排除路径逻辑移到函数内部,既保留了跳过内部路径的需求,又满足Auth.js不允许设置matcher的要求。 - 异步适配:由于Auth.js的
authMiddleware是异步函数,最终的middleware必须声明为async以兼容异步逻辑。
内容的提问来源于stack exchange,提问作者Shridhar
相关产品推荐
相关产品推荐

