In Next.js app, A middleware to handle authentication redirects. Unauthenticated users should be redirected to /login when accessing protected routes like /dashboard. However, navigating to /dashboard causes an infinite redirect loop between /dashboard and /login.
1: Following is the middleware.ts to check for a session cookie. If absent, redirect to /login
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const sessionCookie = request.cookies.get('session');
const { pathname } = request.nextUrl;
// Redirect to /login if no session exists and path is protected
if (!sessionCookie && pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
// Matcher configuration (runs on all paths except /login)
export const config = {
matcher: ['/((?!login|_next/static|_next/image|favicon.ico).*)'],
};
2: Login Page Logic set the session cookie and redirect to /dashboard
// pages/login.tsx
const handleLogin = async () => {
await fetch('/api/login', { method: 'POST' });
window.location.href = '/dashboard'; // Redirect after setting cookie
};
Current Result:
- Visiting /dashboard redirects to /login (expected)
- After logging in, /dashboard briefly loads but redirects back to /login, causing an infinite loop
Expected Result: After login, users should stay on /dashboard without further redirects
Debugging Steps Taken:
- Verified the session cookie is set correctly after login.
- Added console.log in middleware: the cookie exists post-login, but the middleware still triggers a redirect.
- Tested with hard-refresh (Ctrl+F5), which sometimes works, but client-side navigation fails.
Question: Why does the middleware continue redirecting even after the session cookie is set, and how can I resolve the infinite loop?