我有一个可通过以下 http://localhost(这是主应用程序的 url)访问的应用程序和另一个可通过 http://localhost/subapp(这是子应用程序的 url)访问的应用程序,我正在使用 nginx 和 docker 在同一端口 (3000) 上的两个不同容器中运行这两个应用程序。
子应用程序是一个子区域,我在设置中间件功能以检查用户是否已通过身份验证时遇到问题,如果未通过身份验证则阻止用户访问某些页面。
为了实现这一点,我在主应用程序(在 http://localhost 上运行)中有一个身份验证系统(使用 next-auth 构建)。
在子应用程序中,我检查了用户通过身份验证时是否正确设置了 cookie,而当用户未经身份验证访问页面时未设置 cookie,但是由于某种原因未调用中间件函数。
下面是中间件功能在subapp中的实现(运行在http://localhost/subapp):
export { default } from "next-auth/middleware";
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(req: NextRequest, res: NextResponse) {
console.log("TEST"); // this is never printed
const session = req.cookies.get('next-auth.session-token');
if(session)
return NextResponse.next();
else
return NextResponse.redirect(new URL('/signin', req.url)); // this should send the user back to http://localhost/sign-in in case the user is not authenticated
}
export const config = {
matcher: [
"/",
"/subapp/play",
"/subapp/api/:path*",
],
pages: {
signIn: '/signin'
}
}
我也曾尝试使用主应用程序(在 http://localhost 上运行)的中间件功能来阻止用户访问 protected 页面,但它不起作用。
最佳答案
当您在 next.config.js
中设置 basePath: '/subapp',
时,您在 middleware.js
中的匹配器是 “/play”
不是 “/subapp/play”
。如果您在匹配器中包含 subapp
,则永远不会调用中间件。
所以尝试:
export const config = {
matcher: [
"/",
"/play",
"/api/:path*",
],
pages: {
signIn: '/signin'
}
}
关于reactjs - NextJS 中间件功能未在区域中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74415201/