Reputation: 11
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.
ERR_TOO_MANY_REDIRECTS '
How can I config to middleware for admin?
Upvotes: 1
Views: 32
Reputation: 311863
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));
}
}
Upvotes: 0