Project: features
This module adds the real features to CourseHub: signup with Better Auth on Prisma, the course detail page, a secure enroll server action and a protected dashboard. Each feature is built end to end: DB -> lib -> UI.
72.1 The user journey to finish
- Step 1
1.Signup: session cookie is set
- Step 2
2./courses/[slug]: detail page
- Step 3
3.Enroll: server action + login check on the server
- Step 4
4./dashboard: my courses
Every feature end to end: DB -> lib -> UI
72.2 Better Auth with the Prisma adapter
TypeScript
import { betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";import { nextCookies } from "better-auth/next-js";import { db } from "./db"; export const auth = betterAuth({ database: prismaAdapter(db, { provider: "postgresql", }), emailAndPassword: { enabled: true }, plugins: [nextCookies()],});- prismaAdapter(db, { provider: "postgresql" }) stores users and sessions in our own Postgres.
- emailAndPassword turns on email + password login.
- nextCookies() lets server actions set the login cookie.
- Add BETTER_AUTH_SECRET and BETTER_AUTH_URL to .env.
- The Better Auth CLI adds User, Session, Account and Verification models to the schema.
Output
model Enrollment { id Int @id @default(autoincrement()) userId String user User @relation(fields: [userId], references: [id], onDelete: Cascade) courseId Int course Course @relation(fields: [courseId], references: [id]) createdAt DateTime @default(now()) @@unique([userId, courseId])}Output
$ npx prisma migrate dev --name authApplying migration `20261106103729_auth`Your database is now in sync with your schema.- onDelete: Cascade: when a user is deleted, their enrollments are deleted too.
72.3 Signup server action
TypeScript
"use server";import { z } from "zod";import { redirect } from "next/navigation";import { auth } from "@/lib/auth";const Signup = z.object({ name: z.string().min(2), email: z.email(), password: z.string().min(8),});export async function signup(_: string, form: FormData) { const r = Signup.safeParse(Object.fromEntries(form)); if (!r.success) return "Please check your details"; try { await auth.api.signUpEmail({ body: r.data }); } catch { return "Email already registered"; } redirect("/dashboard");}| Input | Result on screen |
|---|---|
| Invalid (name < 2, bad email, password < 8) | Please check your details |
| Email already in use | Email already registered |
| Valid new user | Redirect to /dashboard: "My courses", "Hi Priya", Log out, "No courses yet." |
- safeParse returns success/failure instead of throwing.
- signUpEmail creates the user and, thanks to nextCookies, logs them in.
- Note: this catch swallows every error; module 73 fixes it.
72.4 Course detail page (dynamic route)
React (TSX)
import { notFound } from "next/navigation";import { getCourses, getCourseBySlug } from "@/lib/courses";import { CourseDetail } from "@/components/CourseDetail";export async function generateStaticParams() { const courses = await getCourses(); return courses.map((c) => ({ slug: c.slug }));}export default async function CoursePage({ params,}: PageProps<"/courses/[slug]">) { const { slug } = await params; const course = await getCourseBySlug(slug); if (!course) notFound(); return <CourseDetail {...course} />;}Output
# React 19 CompleteComponents, hooks aur forms.Intermediate · 40 lessons · ₹999[button] Enroll- generateStaticParams returns all slugs at build time, so the pages are prebuilt.
- params is a Promise in Next.js 16: always await it.
- getCourseBySlug is a "use cache" function like getCourses.
- notFound() shows the 404 page when the slug does not exist.
72.5 enrollUser in lib (handling P2002)
TypeScript
export async function enrollUser(userId: string, courseId: number) { try { await db.enrollment.create({ data: { userId, courseId } }); return "Enrolled!"; } catch (e) { const known = e instanceof Prisma.PrismaClientKnownRequestError; if (known && e.code === "P2002") return "Already enrolled"; throw e; }}- P2002 = unique constraint on (userId, courseId) -> friendly "Already enrolled".
- Any other error is re-thrown, never hidden.
72.6 Enroll server action
TypeScript
"use server";import { z } from "zod";import { requireUser } from "@/lib/session";import { enrollUser } from "@/lib/courses"; const CourseId = z.number().int().positive(); export async function enroll(courseId: number) { const user = await requireUser(); const id = CourseId.parse(courseId); return enrollUser(user.id, id);}- requireUser() sends a logged-out user to /login.
- A server action is a public endpoint, so validate courseId with Zod: never trust client data.
- userId always comes from the session, never from the client.
- Step 1
1.Button: form action = enroll.bind(null, courseId)
- Step 2
2.Server action runs on the server
- Step 3
3.requireUser(): no session -> /login
- Step 4
4.Zod validates courseId
- Step 5
5.enrollUser(session user.id, id): create row
- Step 6
6."Enrolled!" or P2002 -> "Already enrolled" back to the UI
72.7 EnrollButton with useActionState
React (TSX)
"use client";import { useActionState } from "react";import { enroll } from "@/app/courses/[slug]/actions";export function EnrollButton(p: { courseId: number }) { const enrollThis = enroll.bind(null, p.courseId); const [msg, action, pending] = useActionState(enrollThis, ""); return ( <form action={action} className="mt-4"> <button disabled={pending}> {pending ? "Enrolling..." : "Enroll"} </button> <p className="mt-2">{msg}</p> </form> );}Output
# React 19 Complete[button] Enrolling... # React 19 Complete[button] EnrollEnrolled! # React 19 Complete[button] EnrollAlready enrolled- bind fixes this course's id onto the action.
- useActionState gives [message, formAction, pending].
- pending disables the button and shows "Enrolling..."; a second press shows "Already enrolled".
72.8 Protected dashboard with Suspense
React (TSX)
import { Suspense } from "react";import { MyCourses } from "@/components/MyCourses"; export default function DashboardPage() { return ( <main className="mx-auto max-w-3xl p-6"> <h1 className="text-2xl font-bold">My courses</h1> <Suspense fallback={<p>Loading...</p>}> <MyCourses /> </Suspense> </main> );}React (TSX)
import { requireUser } from "@/lib/session";import { getMyCourses } from "@/lib/courses";import { CourseCard } from "@/components/CourseCard";import { LogoutButton } from "@/components/LogoutButton";export async function MyCourses() { const user = await requireUser(); const courses = await getMyCourses(user.id); return ( <div className="mt-6 grid gap-4"> <p>Hi {user.name} <LogoutButton /></p> {courses.length === 0 && <p>No courses yet.</p>} {courses.map((c) => <CourseCard key={c.slug} {...c} />)} </div> );}Output
# My coursesHi Priya[button] Log outReact 19 CompleteIntermediate · 40 lessons₹999- The session cookie is known only at request time, so that part sits inside Suspense (cache components are on).
- The heading and the Loading shell are prebuilt; the user's courses stream in.
- getMyCourses is per-user data, so it has no "use cache".
72.9 Checkpoint: remove generateStaticParams?
Output
$ npm run buildError: Route "/courses/[slug]": Next.js encountered uncached or runtime data during prerendering.Export encountered an error on /courses/[slug]/page: /courses/[slug], exiting the build.- The build fails: with cache components, params is runtime data and the build does not know which slugs to prebuild.
- Fix: provide generateStaticParams, or wrap the dynamic part in Suspense.
72.10 Common mistakes
TypeScript
"use server";import { enrollUser } from "@/lib/courses"; export async function enroll( courseId: number, userId: string,) { return enrollUser(userId, courseId);}- Wrong (above): taking userId from the client. Any script can call the action with someone else's userId and enroll in their name. Right: userId from the session (72.6).
- Misconception: check with findFirst, then create. On a double click both requests check at the same time and both pass (race condition).
- The real guarantee is the database unique constraint: just create and handle P2002.
| Data | Where it is read | Cache? |
|---|---|---|
| Course list / course detail (shared) | getCourses, getCourseBySlug | Yes: "use cache" |
| My courses (per user) | getMyCourses inside Suspense | No: read fresh per request |
72.11 Interview tips
- "How would you build a protected feature like enroll?": a server action that first verifies the session, then validates input with Zod.
- Take userId from the session; a unique constraint in the DB stops duplicates, and P2002 becomes a friendly message.
- Show pending and result in the UI with useActionState.
- Mention: await params, generateStaticParams for prebuilt pages, per-user data in Suspense without cache.