I am trying to verify my token in nextjs middleware using jose library. But if any case the code goes into the catch block it enter into a infinite loop and doesn't redirect to the login page.Actually, I have never authenticate token before, so I am kind of confused what I should do now. This problem specially happened when someone change the access token in the browser.This is my code.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from 'jose';
export default async function middleware(request: NextRequest) {
const access = request.cookies.get("access")?.value;
const url = request.url;
const urlStartWithUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/open-bo-account`;
const redirectUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/login/`;
if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
request.cookies.clear()
return NextResponse.redirect(new URL('/login', request.url));
} else if (access) {
try {
const secret = new TextEncoder().encode(
"secret key"
);
const decodedToken = await jwtVerify(access, secret);
if (decodedToken) {
return NextResponse.next();
}
request.cookies.clear();
return NextResponse.redirect(new URL('/login', request.url));
} catch (error) {
const cookiesBeforeClear = request.cookies.getAll();
console.log("Cookies before clear:", cookiesBeforeClear);
request.cookies.clear();
const cookiesAfterClear = request.cookies.getAll();
console.log("Cookies after clear:", cookiesAfterClear);
return NextResponse.redirect(new URL('/login', request.url));
}
}
}
The problem was in the else if block.it should be the following
(access && request.nextUrl.pathname.startsWith('/open-bo-account'))
Full code is like