Skip to content
Discussion options

You must be logged in to vote

The redirect call itself is fine here; middleware redirects are followed as a new request, so the important part is making the route checks segment-safe and mutually exclusive.

const isDashboard = pathname === '/dashboard' || pathname.startsWith('/dashboard/')
const isLogin = pathname === '/login' || pathname.startsWith('/login/')

if (!token && isDashboard) {
  return NextResponse.redirect(new URL('/login', request.nextUrl))
}

if (token && isLogin) {
  return NextResponse.redirect(new URL('/dashboard', request.nextUrl))
}

I would also exclude API routes from the matcher: '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'. If it still loops after that…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@faisalkhandev
Comment options

Answer selected by faisalkhandev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants