Protected route by cookies in middleware not working with App router
Answered
Le Conte's Sparrow posted this in #help-forum
Le Conte's SparrowOP
I have a few routes (RSC) need to be protected by cookies in a middleware.
The matter is the middleware seems to be called only once.
After I finish setCookie in login page and redirect back to protected routes by
I try to put a
The only way I can do now is calling a refresh by
Anyone can explain what happen and how to fix it?
The matter is the middleware seems to be called only once.
After I finish setCookie in login page and redirect back to protected routes by
useRouter().replace('/protected') the middleware not triggered anymore. It just come back to login page.I try to put a
Link inside login page to click back to that route but it still doesn't work.The only way I can do now is calling a refresh by
window.location.reload(); right after setting cookie. But this seems a bit awkward.Anyone can explain what happen and how to fix it?
Answered by Ray
sound like you hit router cache. try this
useRouter().refresh()
useRouter().replace('/protected')4 Replies
@Le Conte's Sparrow I have a few routes (RSC) need to be protected by cookies in a middleware.
The matter is the middleware seems to be called only once.
After I finish setCookie in login page and redirect back to protected routes by `useRouter().replace('/protected')` the middleware not triggered anymore. It just come back to login page.
I try to put a `Link` inside login page to click back to that route but it still doesn't work.
The only way I can do now is calling a refresh by `window.location.reload();` right after setting cookie. But this seems a bit awkward.
Anyone can explain what happen and how to fix it?
sound like you hit router cache. try this
useRouter().refresh()
useRouter().replace('/protected')Answer
Le Conte's SparrowOP
Thanks so much man.
That fixes the issue.
The weird thing is this happens on production only, not on dev mode and took me a lot of time to understand what happened 🥹
That fixes the issue.
The weird thing is this happens on production only, not on dev mode and took me a lot of time to understand what happened 🥹
@Le Conte's Sparrow Thanks so much man.
That fixes the issue.
The weird thing is this happens on production only, not on dev mode and took me a lot of time to understand what happened 🥹
look like the route cached by prefetching which only enable on production