Next.js Discord

Discord Forum

Middleware doesn't fire on browser back button

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
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

11 Replies

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
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.
Just use useEffect to execute code on navigation, it's easier
@fuma Just use `useEffect` to execute code on navigation, it's easier
Polar bear
shouldn't we try to avoid using useEffect
why? it kinda off-topic and useEffect shouldn't be avoided unless you think you have a better alternative
Transvaal lionOP
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
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
For detecting browser back button, use useEffect with pathname as dependency