如何合并NextAuth v5与next-i18n-router中间件(保留原有配置)
合并NextAuth与next-i18n-router中间件(保留原有配置)
针对你的技术栈(Next.js 14、NextAuth 5.0.0-beta.15、next-i18n-router 5.4.0),可以通过链式调用中间件逻辑的方式合并两者,同时完整保留原有配置和功能。
核心思路
- 优先执行
next-i18n-router的路由处理(确保国际化路径重定向完成后,再进行权限校验) - 若i18n路由处理未返回重定向响应,再执行NextAuth的权限控制逻辑
- 合并两者的
matcher规则,覆盖所有需要处理的路径
合并后的完整代码
import authConfig from '@/auth.config'; import NextAuth from 'next-auth'; import { i18nRouter } from "next-i18n-router"; import i18nConfig from "@/i18nConfig"; import { API_ROUTES, authRoutes, DEFAULT_REDIRECT, publicRoutes, } from '@/routes'; import { NextRequest } from "next/server"; // 初始化NextAuth auth实例 export const { auth } = NextAuth(authConfig); // 合并后的中间件函数 export default auth((req: NextRequest) => { // 第一步:执行i18n路由处理 const i18nResponse = i18nRouter(req, i18nConfig); // 如果i18n返回了重定向响应,直接返回 if (i18nResponse) { return i18nResponse; } // 第二步:执行原有NextAuth权限控制逻辑 const { nextUrl } = req; const isLoggedIn = !!req.auth; const isApiAuthRoute = nextUrl.pathname.startsWith(API_ROUTES.AUTH); const isPublicRoute = publicRoutes.includes(nextUrl.pathname); const isAuthRoute = authRoutes.includes(nextUrl.pathname); if (isApiAuthRoute) { return null; } if (isAuthRoute) { if (isLoggedIn) return Response.redirect(new URL(DEFAULT_REDIRECT, nextUrl)); return null; } if (!isLoggedIn && !isPublicRoute) { let callbackUrl = nextUrl.pathname; if (nextUrl.search) { callbackUrl += nextUrl.search; } const encodedCallbackUrl = encodeURIComponent(callbackUrl); return Response.redirect( new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl), ); } return null; }); // 合并后的matcher配置:同时覆盖Auth和i18n的路径需求 export const config = { matcher: [ // 排除静态文件、Next.js内部文件、static目录 '/((?!.+\\.[\\w]+$|_next|static).*)', // 包含api/trpc路径(Auth需要处理) '/(api|trpc)(.*)', ], };
关键说明
- 执行顺序:先处理i18n路由,避免Auth逻辑基于未国际化的原始路径进行判断
- matcher合并:
- 保留了Auth对
api/trpc路径的处理需求 - 加入了i18n需要排除的
static路径 - 继续排除静态文件(带扩展名的文件)和Next.js内部的
_next路径
- 保留了Auth对
- 功能完整性:完全保留了原有两个中间件的所有逻辑,没有修改任何权限判断或国际化路由规则
内容的提问来源于stack exchange,提问作者Александр Мерный
相关产品推荐
相关产品推荐

