最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Next.js Middleware Causing Infinite Redirect Loop with Authentication (Client-Side Navigation) - Stack Overflow

programmeradmin0浏览0评论

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?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论