Next.js Discord

Discord Forum

Page/Layout route revalidation not working?

Unanswered
La Sagra's Flycatcher posted this in #help-forum
Open in Discord
La Sagra's FlycatcherOP
I'm struggling to find a way to protect routes based on user auth. I have a '/' route which is unprotected and has a link to '/account' which is a protected route and should redirect you to '/signup'.

I have tried getting the user session in middleware and then redirecting if necessary, and I have tried getting the user session in a server component route and redirecting if necessary. In both cases, the caching of the server component route means that for a minute or so after auth state changes from signed out to signed in, going to /account still redirects to /signup.

Note that typing the url into the browser's search bar will result in a correct navigation without using the cache. But if you use the <Link> on the '/' path to go to '/account' then the cached route will be used and thus it will redirect incorrectly.

I tried setting export const revalidate = 0, but this did not change the behavior.

Here is the code repository, would super appreciate someone taking a quick look.

https://github.com/bztravis/gifgrams

deployment: https://gifgrams.vercel.app/

13 Replies

Tramp ant
have you lookied intno nextAuth.js?
also try with intercepting routes
@Tramp ant have you lookied intno nextAuth.js?
La Sagra's FlycatcherOP
thanks for your response! I have peeked at it but I'm already using supabase for auth
@Tramp ant ah this could be happening because of client side router caching
La Sagra's FlycatcherOP
yes, this is what I believe is the issue, since using middleware to log the paths being requested reveals that the /account is not actually being requested fresh (it's in the client side router cache)
I tried setting
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-no-store'
export const dynamicParams = true
export const revalidate = 0
in the /account page.js but this didn't have any effect
Barbary Lion
i'm currently using the .refresh() approach as described here: https://github.com/vercel/next.js/issues/42991#issuecomment-1382024752

i think it's an issue that theyre working on fixing.

the thing that wasn't obvious to me until very recently was there there are multiple caches involved. the cache that youre hitting is related to the "Router Cache" on the frontend.

revalidate refers to the "Data Cache", which is a backend cache.
Tramp ant
yeah. you might need to make sure you trigger hard navigation to get rid of the client side router cache
which is why i'd recommend returning a redirect status code from the api if necessary
instead of relying on the nextjs router