#Middleware doesn't fire on browser back button

12 messages · Page 1 of 1 (latest)

dull bane
#

As stated in the title, there seems to be an issue whereby the middleware doesn't trigger when we are clicking on the browser's back button.

It seems like a cache issue because if i refresh the page and press the back button, the middleware seems to trigger.

Based on the documentation

Middleware runs before cached content and routes are matched.

The browser shouldn't return the cached content instead return a new page.

Here is a simple reproducible code
https://github.com/dextersiah/nextjs-reproduction

GitHub

Contribute to dextersiah/nextjs-reproduction development by creating an account on GitHub.

digital ospreyBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

jovial geyser
#

I guess you misunderstood the meaning.
The docs said "before cached content and routes are matched." means if the content/page is cached, it's not executed

#

Because it's basically a layer between server and client, if no requests are sent to server, middleware won't be triggered

fathom spear
#

If you want to have a somewhat reliable way of detecting page navigations you'll have to watch closely the requests made to your website's favicon cause that's the only thing that is requested every time a user navigates to a page no matter what.

jovial geyser
#

Just use useEffect to execute code on navigation, it's easier

quiet fiber
jovial geyser
#

why? it kinda off-topic and useEffect shouldn't be avoided unless you think you have a better alternative

dull bane
#

I see... if that's the case is there a way to handle or detect if a browser back button has been triggered? Because based on my sample, if the user is logged in, they shouldn't be able to access the login page again. Similarly if they have logged out, they would still be able to access the protected page by pressing the back button

jovial geyser
#

But that will be stale data, it’s safe

#

Since it is just cached data, the user can no longer access protected api endpoints and pages anymore

#

And use router.replace instead of push if you don’t wanna leave a history