Next.js Discord

Discord Forum

Middleware redirect not working when navigating to "/"

Unanswered
Mugger Crocodile posted this in #help-forum
Open in Discord
Mugger CrocodileOP
Hello. I have some middleware setup, that checks whether a user is logged in. If they are not, they are redirected to "/login" with NextResponse.redirect(newUrl);. If they are (and the route is not "/login") they are allowed to continue, with NextResponse.next().

This appears to work correctly other than when the user is routed to "/" from the frontend with router.push("/")

In such cases, the middleware detects the user is not logged in, and hits the redirect code correctly (I confirm this with logging prior to the .redirect call), but no subsequent middleware function is run (which seems strange, as a redirect should have been triggered), and the user is sent to "/" on the frontend.

This doesn't happen when there is no prior caching on the front-end, eg after a complete hard reload and/or using a private browser session. I am seeing this in local development.

I have ensured all my NextLink tags have prefetch={false} on them, but I wonder if I'm missing something else obvious.

Thank you for any help.

1 Reply

Mugger CrocodileOP
Hello. I thought I would just bump this once. Thank you