Next.js Discord

Discord Forum

Middleware NextResponse.rewrite does not work on "soft navigation"

Unanswered
Miniature American Shepherd posted this in #help-forum
Open in Discord
Miniature American ShepherdOP
I'm using the pages router, and have a middleware.ts file under the src, the goal of this middleware is to check if the user is authenticated and if they have a role to access /admin pages, if not, rewrite to a /404 page.

This is somewhat working, I can see the requests failing and being rewrited to a 404 page in the Network tab, and if I do a full reload on an /admin page with a regular user, I see the /404 page content.

The issue is, if I navigate using in-page links, so kind of a spa/soft navigation, I can still see the request resulting in 404 and the /404 page being returned by the server, but the page still renders the admin content, and not the /404 page content.
If I change the rewrite to a redirect it works, but a rewrite would be ideal.

Relevant docs: https://nextjs.org/docs/pages/building-your-application/routing/middleware

0 Replies