NextResponse.redirect() not redirecting as expected in Next.js Middleware #97455
SummaryI am experiencing an issue where NextResponse.redirect() inside my Next.js middleware is failing to redirect the page properly, failing silently, or causing an infinite redirect loop. Additional informationimport { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value;
const { pathname } = request.nextUrl;
// Redirect unauthenticated users trying to access protected routes
if (!token && pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Redirect authenticated users away from public auth pages
if (token && pathname.startsWith('/login')) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public static files
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};ExampleNo response |
Replies: 1 comment 1 reply
|
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: |
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.
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…