Based on the code you provided, it seems like you're using Next.js middleware to handle authentication. If a token is found in the cookies, the middleware allows the request to proceed. If not, it redirects the user to the /authentication page.
If you're experiencing an issue where the redirection is happening repeatedly, it could be due to a few reasons:
-
The /authentication page itself might not be setting the token cookie correctly. Ensure that after successful authentication, the token cookie is being set.
-
The middleware is being applied to the /authentication page as well. This would cause a loop where the middleware redirects to the /authentication page, and then the middleware runs again on this page, causing another redirect. To avoid this, you could add a check in your middleware to skip the authentication check for the /authentication page.
Here's an example of how you could modify your middleware to avoid applying it to the /authentication page:
export async function middleware(request: NextRequest) {
console.log("Current URL: ", request.url);
if (request.nextUrl.pathname === '/authentication') {
return NextResponse.next();
}
if (request.cookies.has('token')) {
console.log("Token found, proceeding to the next response...");
return NextResponse.next();
} else {
console.log("Token not found, redirecting to /authentication...");
return NextResponse.redirect('<http://localhost:3000/authentication'>);
}
}
Please note that the code above is based on the information provided in the extracts and may need to be adjusted based on your specific application setup.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: