I am using middleware in Next.js to check user authentication and redirect to the login page if the token is missing. The middleware executes correctly on the first visit to any page, but if I navigate to a page that triggers a redirect, the middleware does not execute again for subsequent redirects to the same page. It only executes again after some time has passed, and then the cycle repeats.
Here is my middleware code:
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { jwtDecode } from 'jwt-decode';
import { TokenUser } from '@/types/common/token-user.type';
export async function middleware(request: NextRequest) {
console.log(request.nextUrl.pathname);
const token = cookies().get('token');
if (!token) {
return NextResponse.redirect(new URL('/auth/login', request.url));
}
if (request.nextUrl.pathname.startsWith('/admin')) {
const user = jwtDecode<TokenUser>(token.value);
if (!user.isSuperAdmin)
return NextResponse.redirect(new URL('/404', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|auth).*)'],
};
Why does the middleware in Next.js only execute once for each page and not on subsequent redirects to the same page? How can I ensure the middleware executes on every request, regardless of previous redirects?