I am having trouble with redirecting a user to /login if the authentication token from Laravel is invalid. I am attempting to retrieve the user and, if resp.ok() returns false, delete the invalid "token" cookie and direct the user to /login. However, I continue to encounter errors in my browser.
The issue seems to be related to the third if-statement in the code snippet below.
Error: The page isn’t redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
// Add protected routes here
const url = req.nextUrl.clone();
if (req.nextUrl.pathname === "/login" && req.cookies.has("token")) {
url.pathname = "/";
return NextResponse.redirect(url);
}
if (
!req.cookies.has("token") &&
req.nextUrl.pathname !== "/login" &&
!req.nextUrl.pathname.startsWith("/_next")
) {
url.pathname = "/login";
return NextResponse.redirect(url);
}
if (req.cookies.has("token")) {
const user = await fetch(`http://10.129.23.206:8080/api/user`, {
headers: {
"Authorization": `Bearer ${req.cookies.get("token")}`,
}
})
console.log(user)
if (!user.ok){
req.cookies.delete("token")
url.pathname = "/login";
return NextResponse.redirect(url)
}
}
}
export const config = {
matcher: ["/", "/create", "/search", "/:slug*", "/login"],
};