Next.js Discord

Discord Forum

Can I disable middleware caching?

Answered
Devon Rex posted this in #help-forum
Open in Discord
Devon RexOP
I'm currently running authentication in my middleware, which is very convenient. However, it seems that once the app runs the middleware for a certain route, if I navigate back to that route, it doesn't get run again.

This is a problem because of this:

I go to "/", which authenticates the user, then I sign out, which takes me to "/login". This also removes the credentials stored in cookies
After logging in, the app takes me back to "/". However, the middleware does not run this time, so I'm unable to fetch and store user-specific details in the cookies.


Is it possible to disable the caching of the middleware? I can't find this in the docs. If there's a preferred method of doing this I'd be happy to try it as well.
Answered by Devon Rex
I tried that, it doesn't work.

I'm going with the router.refresh method, so basically I call router.refresh whenever I would router.push across authentication boundaries. It feels a little janky, but it technically works for now.

Thanks for the help
View full answer

13 Replies

Devon RexOP
Is that the only solution? It seems excessive to be forced to refresh the page every time something like this happens
Devon RexOP
I tried that, it doesn't work.

I'm going with the router.refresh method, so basically I call router.refresh whenever I would router.push across authentication boundaries. It feels a little janky, but it technically works for now.

Thanks for the help
Answer
And use it wherever you like
This is not a suitable solution for this issue, but I’m unable to find any other solution
@Devon Rex Just a update, I found a solution
https://nextjs.org/docs/app/building-your-application/caching#invalidation-1


#CLIENTSIDECACHE (tags are for so it’s easy for me to find)
logout using cookies().delete()
Devon RexOP
Thanks, that's a good note. I generally log out from the client side, but I did have to remove some cookies, so I have some cookie deletion in the middleware as well