Deviopath › Next.js

Redirect After Logout

Medium · Navigation

Sometimes the client finds out that the user must leave the page, for example after logging out. useRouter() from next/navigation can navigate from code:

- router.push(url) adds a history entry.

- router.replace(url) **replaces** the current one, so the Back button does not return to the protected page. Use it for redirects.

Navigation is a side effect, so do it in useEffect, not while rendering.

(If the server already knows the user is logged out, prefer a server-side redirect: redirect("/login") in a Server Component, or a check in proxy.ts. Then the protected page never renders at all.)

The user state and the "Log out" button are already written. Update DashboardPage:

- While user is set, show Welcome, <name> in the <h1> and the "Log out" button.

- When user becomes null, call router.replace("/login") from an effect, and render <p>Redirecting…</p> instead of the welcome text and button.

(In this preview the component stays on screen after the URL changes. In a real app the login page would replace it.)

Next: Photo Modal with a Real URL