next js middleware infinite redirect

I have three pages in my app register , login , home if user is not logged he gets redirected to login page , the home page is accessed only if the user is authenticated which is determined if there is a cookie in the browser I wanna implement protected routes via next js middleware scenario : I am having a issue when I login I am redirected to the home page if I go i should be redirected to the home page the previous page is the login page when I do that problem: i get a too many redirects error for a moment then I am redirected to home page as expected I inspected the network tab there is a pattern that goes like this before i am finally redirected to the home page /login page requested (307 temporary redirect) ,
/home page requested(307 temporary redirect) repeated several times , I also wanna mention that this happens when i am at the login page and try to go to forward and backward pages and get redirected to login since i am not logged in and then login get redirected to home page and try to go back here is the code
 import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest, response: NextResponse) {
  const isUserLogged = request.cookies.get('chat_accessToken');
  const pathname = request.nextUrl.pathname;
  console.log('pathname', pathname);
  const authPaths = ['/login', '/register'];
  if (
    (isUserLogged && pathname == '/') ||
    (isUserLogged && authPaths.includes(pathname)) ||
    (isUserLogged && pathname !== '/home/chats')
  ) {
    return NextResponse.redirect(new URL('/home/chats', request.url));
  }
  else if (!authPaths.includes(pathname) && !isUserLogged) {
    return NextResponse.redirect(new URL('/login', request.url));
  } else if (!isUserLogged && authPaths.includes(pathname)) {
    return NextResponse.next();
  }
  return NextResponse.next();
}
export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};
Was this page helpful?