Next.js Discord

Discord Forum

How to stop middleware error page endless refresh?

Unanswered
Blanc de Hotot posted this in #help-forum
Open in Discord
Avatar
Blanc de HototOP
Hi

I have a middleware that validates the user's auth, checks if he has access role for that route, and either allows him to access the page or redirects him to the login.

My problem is that when the user is allowed to access a route ("./admin/.") but gets some error, like 404 page not found or something else, then his page refreshes endlessly.

A showcase of the middleware file and the video showcasing the endless refresh are attached.

Does anyone know what I can do to stop the page from refreshing endlessly. I have identified that the problem is with returning res, a TODO is set in the code.

Best regards Aron
Image
Image

2 Replies

Avatar
SupremeDeity
Haven't read that code in detail but i think the problem is that you arent checking if the destination of your redirect is the same as your current path.

Middleware runs before every request meaning its probably continuously redirecting you to login page because its failing the other checks, which in turn would re-run the middleware.
Avatar
Blanc de HototOP
Hi, thank you for your reply.

Unfortunately, that is not the problem. When I compare req.nextUrl.pathname and req.url, they are always the same.

The problem is not with the login but rather when the user is allowed to access a page, but there is some next js error like page not found or application error, then the site all of a sudden goes into this crazy endless refresh, like demonstrated in the video :/