Login Flow with Redirects
Hard · Authentication
Build a small login flow with client-side redirects. One App renders the page for the current usePathname(): / (home), /login and /dashboard.
login(email, password) in the starter is a fake Server Action (30 ms). It returns { ok: true, user } for ada@example.com / secret123 and { ok: false, error: "Invalid email or password" } otherwise. Keep the user in React state inside App.
- /login: a <form> with <input name="email">, <input name="password" type="password"> and <button type="submit">Log in</button>. Trim and lowercase the email. If a field is empty, show Email and password are required without calling the action.
- While the action runs, the button shows Logging in… and is disabled. On failure show the error in <p className="error"> and clear the password field. On success store the user and router.push("/dashboard").
- /dashboard shows <h1>Welcome, Ada</h1>, a <Link href="/">Home</Link> and a Log out button. When nobody is logged in, never render the dashboard; call router.replace("/login") instead (replace, so the back button does not return to a page that only redirects).
- Log out clears the user and replaces the URL with /login.
- Opening /login while logged in replaces the URL with /dashboard.
- / shows <Link href="/dashboard">Dashboard</Link>, <Link href="/login">Log in</Link> and, when logged in, <p className="who">Signed in as Ada</p>.
In a real app the session lives in an httpOnly cookie and the check runs on the server (in proxy.ts, or with redirect() in a Server Component). Client-side redirects are only UX, never security.