Next.js Discord

Discord Forum

How to prevents user to go back once logout

Unanswered
Gazami crab posted this in #help-forum
Open in Discord
Gazami crabOP
Hey guys, I have an dashbaoard page which is protected page, it is only accessible if there is some auth cookie else it will redirect user to login page.
Let say I am in some dashboard/settings page or some other protected page and user gets logout by clearing cookies and all auth related data and user gets redirected to the login page. But if use try to goback than it takes the user to dashboard page and all pages which acces. Intried with router.replace but than its working as same.
How should I handle this scenario

6 Replies

American Chinchilla
You use middleware for this
By checking the path for anything matching the parent protected route
And in thr server component you double check if their auth otherwise call redirect
Gazami crabOP
Yes middleware is working but don’t know why not working when going back
American Chinchilla
Could be due to some caching wirh fetching permission or renewing sessions/tokens. not really sure without seeing the code for the file
@Gazami crab Yes middleware is working but don’t know why not working when going back
“Going back”, do you mean the default browser backwards (and forwards) navigation?

If you navigate through Next.js links it should work since you’re requesting the page again, but for browser navigation Next.js reuses the React Server Component payload that’s cached in the Client Router Cache for instant navigations.

When you perform the action of “deleting the cookie” make sure to purge the router cache, for this you can use revalidatePath() or router.refresh().
And keep your middleware too, this will prevent users from accessing to your protected pages when navigating through Next.js Links or hard navigation via the URL