admin管理员组

文章数量:1419168


  if (
    adminconfig?.matcher.includes(pathname) ||
    pathname.startsWith("/admin/")
  ) {
    if (!isAuthenticated) {
      return NextResponse.redirect(new URL("/", request.nextUrl));
    } else if (isAdmin) {
      return NextResponse.redirect(
        new URL("/admin/main/users", request.nextUrl)
      );
    } else {
      return NextResponse.redirect(new URL("/not-admin", request.nextUrl));
    }
  }

if user's role is admin, he/she can redirecting admin url. If not, redşrecting not-admin page.

not-admin redirecting is working. But if user is admin, admin/main/users or admin/path* not working. The error:

'This page isn’t working

localhost redirected you too many times.

  • Try deleting your cookies.

ERR_TOO_MANY_REDIRECTS '

How can I config to middleware for admin?


  if (
    adminconfig?.matcher.includes(pathname) ||
    pathname.startsWith("/admin/")
  ) {
    if (!isAuthenticated) {
      return NextResponse.redirect(new URL("/", request.nextUrl));
    } else if (isAdmin) {
      return NextResponse.redirect(
        new URL("/admin/main/users", request.nextUrl)
      );
    } else {
      return NextResponse.redirect(new URL("/not-admin", request.nextUrl));
    }
  }

if user's role is admin, he/she can redirecting admin url. If not, redşrecting not-admin page.

not-admin redirecting is working. But if user is admin, admin/main/users or admin/path* not working. The error:

'This page isn’t working

localhost redirected you too many times.

  • Try deleting your cookies.

ERR_TOO_MANY_REDIRECTS '

How can I config to middleware for admin?

Share Improve this question edited Jan 29 at 8:11 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Jan 29 at 8:08 Gülbeyaz BAYRAM ÖZERGülbeyaz BAYRAM ÖZER 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You have a logical flaw here - if the path starts with /amdin and the user is authenticated as an admin, they're redirected to /admin/main/users. The problem is that that path also starts with /admin, so it's ridercted again and so on, until it fail with ERR_TOO_MANY_REDIRECTS.

One approach to solve this is to not redirect if the URL is already /admin/main/users:

if (
    adminconfig?.matcher.includes(pathname) ||
    pathname.startsWith("/admin/")
  ) {
    if (!isAuthenticated) {
      return NextResponse.redirect(new URL("/", request.nextUrl));
    } else if (isAdmin &&
               !pathname.startsWith("/admin/main/users")) { // Here!
      return NextResponse.redirect(
        new URL("/admin/main/users", request.nextUrl)
      );
    } else {
      return NextResponse.redirect(new URL("/not-admin", request.nextUrl));
    }
  }

本文标签: nextjsMiddleware admin configurationStack Overflow