October 22, 2024
Chicago 12, Melborne City, USA
javascript

next js middleware infinite redirects


I want to protect my home page if the user is not authenticated he shouldn’t have access to it , a user is authenticated if a cookie exists , if the user is logged in and attempts to change url to login page he should get redirected to home page using next js middleware the problem is if I go back and forth between pages in this case the login page and then sign in i get redirected to login page as expected , the page before the home page is now the login page if i attempt to go back i get a too many redirects message on the screen for a few seconds before i am redirected to home page as expected i have attached a screen shot of my requests from the network tab when this issue occurs network tab i have been stuck with this issue for a few days and it’s really frustrating . `

import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest, response:
NextResponse) {

const isUserLogged = request.cookies.get('chat_accessToken');

const pathname = request.nextUrl.pathname;
const authPaths = ['/login', '/register'];

if (
 (isUserLogged && pathname == '/') ||
 (isUserLogged && authPaths.includes(pathname) && pathname !== '/home/chats')
) {
 return NextResponse.redirect(new URL('/home/chats', request.url));
}
if (!pathname.includes('/login') && !isUserLogged) {

   return NextResponse.redirect(new URL('/login', request.url));
 } 
   return NextResponse.next();

 }
export const config = {
   matcher: [
  /*
   * Match all request paths except for the ones starting with:
   * - api (API routes)
   * - _next/static (static files)
   * - _next/image (image optimization files)
   * - favicon.ico (favicon file)
   */
   '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

`

i have changed a condition to ensure that the page doesn’t redirect to itself (didn’t work)



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video