I am trying to redirect a user to /login if the authentication token from Laravel is not valid. So I am trying to fetch the user and if resp.ok() is false then I delete the invalid "token" cookie and redirect the user to /login. But I keep on getting errors in my browser.
It is about the third if-statement in the code sample down 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"],
};
2
Answers
I think fetching user is failing and then in this
if
blockyou are deleting the token, after that when you make another request wihtout token, so this
if
gets executed and you are redirected to "login" again:fetching user code should be
try/catch
block, and in catch block you should handle the error accordingly. maybe you send the message to the browser, browser will display the error on form instead of redirecting again.This is how I implemented it in my NextJS middleware.
As NextJS middleware (the Edge Runtime) does not support Node.js APIs and globals, it should be a better way to continue some NodeJS operations in API router.