Skip to lesson content

PROJECT 5 · LESSON 14 OF 18

Build the account screens

Create an account, sign in, show a session and sign out.

  • auth client
  • pending feedback
  • session reads
  • redirect

Your workspace: task-app

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.

1. Understand the problem and the concepts

Why we need this feature

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.

One form, two account operations

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.

Read success, failure and pending states

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.

Signing out changes server identity, not just the visible page

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The learner submits credentials in a client form.

  2. The auth client calls the appropriate provider endpoint.

  3. On success the provider establishes the session and the router refreshes the view.

  4. The Account Server Component independently reads that session and displays the verified user.

Follow registration through to logout

  1. Choose Create a new account and enter a learning name, email and password.
  2. The client invokes signUp.email; a successful response leads to /.
  3. Open /account. requireUser reads the request session and returns the same registered identity.
  4. Click Sign out, then revisit /account. The absent session now sends you back to sign-in.

3. Build it, one file at a time

  1. Add /sign-in, /account and SignOut.
  2. Open /sign-in, choose Create a new account, and register. Then open /account.
  3. Sign out and revisit /account; requireUser redirects you to sign-in.

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.

app/sign-in/page.tsx

This is the interactive account form for registration and sign-in.

app/sign-in/page.tsx
"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>
    </>
  );
}

Read the code

  1. register selects a UI mode; pending tracks the request; message displays a failure. None of these booleans substitutes for a verified server session.
  2. submit prevents the normal form navigation, collects named fields, and calls the provider method for the selected mode. A returned error stops the success branch.
  3. On success, replace moves away from the sign-in screen and refresh updates server-rendered session-dependent content. finally restores the button after either outcome.

components/sign-out.tsx

This ends the provider session before updating navigation.

components/sign-out.tsx
"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>
    </>
  );
}

Read the code

  1. The handler waits for signOut and checks its result. A failed request leaves a visible error instead of claiming success.
  2. After success, replace goes to sign-in and refresh invalidates the current server-rendered view. Hiding a user’s name without ending the session would not be logout.

app/account/page.tsx

This displays account details only after the server verifies the current session.

app/account/page.tsx
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 />
    </>
  );
}

Read the code

  1. requireUser runs before the returned JSX. Without a valid session it redirects and no account content is rendered.
  2. The displayed name and email come from that verified user object, not from a URL parameter. SignOut is a client control composed into the server page.

app/layout.tsx

This defines the document and shared structure surrounding the selected page.

app/layout.tsx
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>
  );
}

Read the code

  1. html and body belong to this root layout. children is the selected route content and must appear in the returned tree.
  2. Shared navigation belongs here so individual pages do not copy it. Link destinations are URL paths, not source filenames.
  3. The stylesheet import applies the shared presentation. The metadata export describes the document rather than rendering visible content.

4. Run it and check your result

  • A new account can sign in and see its name.
  • Invalid credentials show an error; signing out prevents account access.

5. Predict, change and observe

Enter a wrong password for an existing learning account, then correct it and submit again.

Compare your prediction with the expected result

What you should observe

The first attempt stays on the form with feedback. The second reaches the signed-in flow.

Why it happens

The client branches on the provider result instead of assuming that resolving a network request means credentials were accepted.

6. Troubleshoot with evidence

A common mistake

A protected account page does not automatically protect task reads or writes. Complete the next lesson.

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.

Two tabs unexpectedly show the same user.

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.

7. Practice and explain it back

Your independent task

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.

Does register=true mean the user is signed in?

No. It only changes the form mode. The provider’s verified server session establishes signed-in identity.

Why check errors during sign-out?

If the sign-out request fails, the session may still be active. Navigating away alone would give a misleading impression that it ended.