Account still shows old signed-out content after login.
Likely cause: The route was changed without refreshing server-rendered session-dependent output.
Check and correct: Keep the router.refresh call after a successful provider operation.
PROJECT 5 · LESSON 14 OF 18
Create an account, sign in, show a session and sign out.
Continue from lesson 13: Configure authentication for the task app. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
The provider is connected, but learners still need a screen for credentials and a visible way to confirm their session. This lesson follows a complete account journey and explains how browser state and server-rendered account data stay aligned.
The browser submits credentials to the auth route and receives a session cookie. The account page reads the session on the server. It does not trust a user ID supplied by the browser.
Use your own test email addresses and learning passwords. This lab does not configure email verification or password reset delivery; add those before turning it into a public service.
register is a UI boolean selecting between creating an account and signing in. It does not determine whether the user is authenticated. In registration mode the form asks for a name and calls signUp.email; in sign-in mode it calls signIn.email with email and password.
event.preventDefault prevents a traditional form navigation because this client handler performs the provider call itself. FormData reads the submitted fields from event.currentTarget, the form. The password input hides the typed characters visually; that alone is not encryption or authentication. The provider and HTTPS deployment handle the actual credential exchange.
pending disables repeated ordinary submissions while awaiting the provider. A returned error is displayed to the learner and stops the success path. A thrown connection failure produces a separate retry message. finally restores the button even when an error branch returns early.
After success, router.replace("/") takes the learner to the task page without retaining the sign-in page as the immediate history entry. router.refresh asks for fresh server-rendered output, so server components read the updated session rather than displaying an earlier signed-out result.
The client does not manually create a session cookie or store the password in localStorage. The provider’s response establishes the session. The Account page verifies it again through requireUser before displaying the name and email.
A real sign-out calls authClient.signOut and checks that it succeeds before navigating away. Simply changing a React boolean or hiding the account panel would leave the session active. Refreshing after sign-out makes the server-rendered view reflect the missing session.
Use separate browser profiles when comparing two users. Tabs in one profile generally share the same origin’s cookies, so signing in as B can also change the identity observed by A’s tab. That is session sharing, not proof that authorization failed.
This learning setup has no email-delivery flow for verification or password recovery. Authentication works for the lab, but those account-lifecycle features need deliberate configuration before accepting real public users.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The learner submits credentials in a client form.
The auth client calls the appropriate provider endpoint.
On success the provider establishes the session and the router refreshes the view.
The Account Server Component independently reads that session and displays the verified user.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This is the interactive account form for registration and sign-in.
"use client";
import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
export default function SignIn() {
const router = useRouter();
const [register, setRegister] = useState(false);
const [message, setMessage] = useState("");
const [pending, setPending] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setPending(true);
setMessage("");
const data = new FormData(event.currentTarget);
const email = String(data.get("email"));
const password = String(data.get("password"));
try {
const result = register
? await authClient.signUp.email({
name: String(data.get("name")),
email,
password,
})
: await authClient.signIn.email({ email, password });
if (result.error) {
setMessage(result.error.message ?? "Sign-in failed.");
return;
}
router.replace("/");
router.refresh();
} catch {
setMessage("Unable to connect. Try again.");
} finally {
setPending(false);
}
}
return (
<>
<h1>{register ? "Create an account" : "Sign in"}</h1>
<form onSubmit={submit}>
{register && (
<label>
Name <input name="name" required autoComplete="name" />
</label>
)}
<label>
Email{" "}
<input name="email" type="email" required autoComplete="email" />
</label>
<label>
Password{" "}
<input
name="password"
type="password"
minLength={8}
maxLength={128}
required
autoComplete={register ? "new-password" : "current-password"}
/>
</label>
<button disabled={pending}>
{pending ? "Please wait…" : register ? "Create account" : "Sign in"}
</button>
<p role="status">{message}</p>
</form>
<button
disabled={pending}
onClick={() => {
setRegister(!register);
setMessage("");
}}
>
{register ? "Use an existing account" : "Create a new account"}
</button>
</>
);
}
This ends the provider session before updating navigation.
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
export default function SignOut() {
const router = useRouter();
const [pending, setPending] = useState(false);
const [error, setError] = useState("");
return (
<>
<button
disabled={pending}
onClick={async () => {
setPending(true);
setError("");
try {
const result = await authClient.signOut();
if (result.error) {
setError("Could not sign out.");
return;
}
router.replace("/sign-in");
router.refresh();
} catch {
setError("Connection failed. Try again.");
} finally {
setPending(false);
}
}}
>
Sign out
</button>
<p role="status">{error}</p>
</>
);
}
This displays account details only after the server verifies the current session.
import { requireUser } from "@/lib/session";
import SignOut from "@/components/sign-out";
export default async function Account() {
const user = await requireUser();
return (
<>
<h1>Hello, {user.name}</h1>
<p>{user.email}</p>
<SignOut />
</>
);
}
This defines the document and shared structure surrounding the selected page.
import type { ReactNode } from "react";
import Link from "next/link";
import "./globals.css";
export const metadata = { title: "My task lab" };
export default function Layout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<nav>
<Link href="/">Tasks</Link>
<Link href="/account">Account</Link>
</nav>
<main>{children}</main>
</body>
</html>
);
}
Enter a wrong password for an existing learning account, then correct it and submit again.
The first attempt stays on the form with feedback. The second reaches the signed-in flow.
The client branches on the provider result instead of assuming that resolving a network request means credentials were accepted.
A protected account page does not automatically protect task reads or writes. Complete the next lesson.
Likely cause: The route was changed without refreshing server-rendered session-dependent output.
Check and correct: Keep the router.refresh call after a successful provider operation.
Likely cause: They share the browser profile’s cookies.
Check and correct: Use a separate browser profile or isolated private session for the second user in ownership tests.
Add a link from the sign-in page back to the task list.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
No. It only changes the form mode. The provider’s verified server session establishes signed-in identity.
If the sign-out request fails, the session may still be active. Navigating away alone would give a misleading impression that it ended.