下一个js的中间件在重定向时重复调用

问题描述 投票:0回答:1

下一个js的中间件在根据条件重定向用户时重复调用,当我通过检查会话存在来检查用户的登录状态并尝试根据用户的角色重定向用户时,我收到“太多重定向错误” “在浏览器上。

仅当我尝试将登录用户重定向到 /admin 页面时,才会发生此错误,但令人惊讶的是,当我尝试将未登录用户重定向到 /login 页面时,它工作正常,但同一行代码是不适用于 /admin 页面

这条👇线不起作用

return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/admin`);

这条👇线正在运行

return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/login`);

这是我的 middleware.js 页面的完整代码

export { default } from "next-auth/middleware";
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(request) {
  const session = await getToken({
    req: request,
    secret: process.env.NEXTAUTH_SECRET,
  });

  const userRole = session?.user?.role.toLowerCase();
  const { nextUrl } = request;

  if (session !== null) {
    if (userRole === "admin" && nextUrl.pathname === "/admin") {
      return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/admin`); // this one is not working
  } else {
    if (
      nextUrl.pathname === "/admin"
    ) {
      return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/login`); // this one is working
    }
  }
}

export const config = {
  matcher: ["/admin/:path*", "/donor/:path*", "/agent/:path*"],
};
reactjs next.js middleware next.js13
1个回答
0
投票

这个

Too Many Redirectes
错误通常在存在重定向循环时发生。在您的
middleware.js
代码中,如果用户具有“管理员”角色并且他们尝试访问
/admin
页面,您会将他们重定向回
/admin
页面,这会导致无限循环。

if (session !== null) {
  if (userRole === "admin" && nextUrl.pathname === "/admin") {
    return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/admin`); // this creates a loop
  }
}

当用户已经处于

/admin
状态时,您不应将其重定向到
/admin
,而应该让请求继续进行。您可能需要这样调整:

if (session !== null) {
  if (userRole === "admin" && nextUrl.pathname !== "/admin") {
    // Redirect admin users to the /admin page if they are not already there
    return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/admin`);
  }
  // If an admin is already on /admin, do nothing (allow the request to proceed)
} else {
  if (nextUrl.pathname.startsWith("/admin")) {
    // Redirect non-authenticated users trying to access /admin to the /login page
    return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/login`);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.