Next.js Discord

Discord Forum

Revalidate router cache from middleware

Unanswered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
Is there a method to invalidate browser/router cache from middleware? Browser caching of server components, specifically layout.tsx and template.tsx, prevents re-rendering unless explicitly instructed. Revalidat path or tag are unsuitable as they clear all caches and are inaccessible from middleware. NextResponse.redirect is also ineffective. The optimal solution appears to be setting a cookie, then monitoring for its presence within a client component. Upon detection, router.refresh can selectively refresh server components without impacting client component state or requiring a hard refresh.

The server component root layout fetches user details and passes them as props to the client component navbar, which conditionally renders a sign-in or sign-out button based on user authentication state. However, when the middleware invalidates the user session by deleting response cookies, the layout fails to re-render, incorrectly displaying the user as logged in. A hard refresh does cause the layout to rerender

8 Replies

Try that out
Revalidating from a server action
ChartreuxOP
That won't work from middlware
@Chartreux That won't work from middlware
Yea, what you can do is fetch the data with unstable cache in the layout and then when you log out.. run a server action there to revalidate the unstable cache directly
ChartreuxOP
Maybe you are not following my main problem. This is for when a user session is expired in the middleware. We delete the cookies in the middleware that save the session id. But the layout does not rerender to show the user that their session is expired.
You don’t use a layout for this, in the case you need the “layout” to show certain state, you will need a client component and somehow notify this client component of the event so it can render whatever state properly
ChartreuxOP
So my layout renders an client component "navbar" the layout fetches the user details by the access token. And then passes props to the navbar. When session expires via refresh I'm middlware I had to figure out how to notify browser to clear router cache.