I am struggling to create a simple jwt cookie authentication middleware where what I want is if there is no cookie to redirect to login and if there is to redirect to dashboard route
here is my current middleware.ts file
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import Routes from './constants/Routes';
export function middleware(request: NextRequest) {
const token = cookies().get('token')?.value;
const isLoginRoute = request.nextUrl.pathname === Routes.LOGIN;
if (!token && !isLoginRoute) {
return NextResponse.redirect(new URL(Routes.LOGIN, request.url));
} else if (isLoginRoute && token) {
return NextResponse.redirect(new URL(Routes.CALCULATE, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [`${Routes.DASHBOARD}/:path*`, Routes.LOGIN],
};
But I am always getting too many redirects and the website is crashing. What should I do ?
I tried to remove the redirect it works but how will I redirect to login if no token
I am expecting the redirection to work without the website crashing