我目前正在开发一个 Next.js 14 应用程序,该应用程序使用 NextAuth 进行身份验证,并使用 Next-i18n-router 进行翻译。我已遵循这两个库的文档,但我遇到了中间件配置问题。
问题是,当与 Next-i18n-router 的中间件结合使用时,NextAuth 的中间件似乎停止工作。我已遵循这两个库的文档,但我可能遗漏了某些内容或存在冲突。
这是我的代码:
// middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import { i18nRouter } from 'next-i18n-router';
import i18nConfig from './i18nConfig';
import { NextRequest } from 'next/server';
export default NextAuth(authConfig).auth;
export function middleware(request: NextRequest) {
return i18nRouter(request, i18nConfig);
}
// only applies this middleware to files in the app directory
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};
您可能会在 Next.js 应用程序中遇到 NextAuth 和 Next-i18n-router 集成问题。如果配置不正确,Next.js 中的中间件有时会出现冲突或问题,特别是在集成多个中间件功能时。
组合中间件函数:不要单独导出它们,而是将
NextAuth
和 Next-i18n-router
中间件函数组合成一个函数。这可确保两个中间件进程在同一上下文中处理。
顺序执行:确保中间件函数顺序执行。如果一个中间件依赖于另一个中间件的结果,这一点可能至关重要。
错误处理:添加错误处理以捕获并解决中间件执行期间出现的任何问题。
以下是您如何修改
middleware.ts
的示例:
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import { i18nRouter } from 'next-i18n-router';
import i18nConfig from './i18nConfig';
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(request: NextRequest) {
try {
// First, handle authentication
const authResponse = await NextAuth(authConfig).auth(request);
if (authResponse instanceof NextResponse && !authResponse.ok) {
return authResponse; // If auth fails, return the response
}
// Then, handle internationalization
const i18nResponse = i18nRouter(request, i18nConfig);
return i18nResponse;
} catch (error) {
// Handle any errors that occur during middleware execution
console.error("Middleware Error:", error);
return new NextResponse("Internal Server Error", { status: 500 });
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};