The store shows an empty catalog.
Likely cause: Products were not seeded into the database selected by the web app.
Check and correct: Check MONGODB_DB in .env.local and run the seed command from the store folder.
PROJECT 6 · LESSON 16 OF 18
Resume EduShop, replace file reads and add customer accounts.
Continue from lesson 9: Keep a guest cart after refresh. 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 task app taught server reads, mutations and sessions with a small model. Return to the existing store and reuse those ideas without rebuilding the product UI. The central exercise is changing the data source while preserving a clear presentation contract.
Return to your EduShop folder from lesson 9, or use this checkpoint. The task application remains a separate project. This lesson copies the auth pattern into the learner’s store; it does not alter EduPoly’s authentication system.
Use MONGODB_DB=edupoly_store_lab and a fresh auth secret. The cart remains a guest cart on this browser; signing in does not upload it. Account-based cart synchronization is an independent extension.
Use a MongoDB Atlas cluster or a replica set for this project: the final lesson uses a transaction for inventory and orders. A standalone MongoDB server cannot run that transaction.
Start from the store checkpoint in lesson 9, not from the task app’s home page. The completed checkpoint already combines the store with the auth modules needed here. The starting-code link intentionally points back to the guest-cart lesson.
Choose edupoly_store_lab as the store database. This prevents task exercises, auth experiments and store products from being mixed accidentally. Use your own fresh secret and matching local origin. The student store is a separate practice application; none of this changes EduPoly’s account system.
lib/store.ts adds stock and active to the familiar Product shape. getProducts queries active records, sorts them and returns plain product objects. The MongoDB-specific _id is removed at the presentation boundary; the public product id remains the cart’s identifier.
The catalog awaits getProducts before applying its existing search and sort logic. The details page awaits getProduct(slug) instead of searching the original array. ProductCard still receives a product object and does not need to know which storage engine supplied it.
The cart page becomes a Server Component that reads the latest active products and passes them to the interactive CartContents component. Quantities remain browser state, while displayed catalog facts come from the server. A missing catalog record is labelled unavailable; authoritative checkout will reject it.
The seed script establishes unique indexes on id and slug. Uniqueness must be enforced by the database, not just by a form lookup that could race with another request. It then upserts each starter product using $setOnInsert, which applies values only when a new record is inserted.
Rerunning the seed therefore does not reset an edited price or refill stock. That is deliberate: initialization should not silently undo learning changes. Run the command with --env-file=.env.local because this standalone Node script is outside Next.js’s automatic environment loading.
The script closes its client when finished. The web app uses a longer-lived client because it handles many requests. Those different lifetimes explain why the same connection pattern is not copied blindly everywhere.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
A product route calls the server-only store data module.
MongoDB returns active product records.
The data module returns plain product values to the page.
Existing cards and interactive cart consumers render those values; auth separately identifies customers when required.
npm install
node --env-file=.env.local scripts/seed.mjs
npm run devThe 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 project’s dependency and command manifest. It tells npm what to install and how to run the learner application.
{
"name": "edupoly-nextjs-lab",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"next": "16.3.0",
"react": "19.2.8",
"react-dom": "19.2.8",
"mongodb": "7.5.0",
"better-auth": "1.6.26",
"server-only": "0.0.1"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19"
}
}
This creates and shares the server-side database client and selects the learning database.
import "server-only";
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Set MONGODB_URI in .env.local");
const globalDB = globalThis as typeof globalThis & {
courseClient?: MongoClient;
};
export const client = globalDB.courseClient ?? new MongoClient(uri);
if (process.env.NODE_ENV !== "production") globalDB.courseClient = client;
export const db = client.db(process.env.MONGODB_DB ?? "edupoly_tasks_lab");
This configures the server authentication provider and its persistent storage adapter.
import "server-only";
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client, db } from "./db";
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
database: mongodbAdapter(db, { client }),
emailAndPassword: { enabled: true },
});
This creates the browser-facing auth helper used by sign-in and sign-out controls.
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();
This provides one server-side way to require the current request’s authenticated user.
import "server-only";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "./auth";
export async function requireUser() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/sign-in");
return session.user;
}
This mounts the auth provider’s HTTP interface inside the App Router.
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);
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 is a list of configuration names and placeholder values to copy into .env.local.
MONGODB_URI=mongodb://127.0.0.1:27017/?replicaSet=rs0
MONGODB_DB=edupoly_store_lab
BETTER_AUTH_URL=http://localhost:3000
BETTER_AUTH_SECRET=replace-with-your-random-secret
This initializes the learning store’s product records and uniqueness constraints.
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
try {
const products = client.db(process.env.MONGODB_DB).collection("products");
await products.createIndex({ id: 1 }, { unique: true });
await products.createIndex({ slug: 1 }, { unique: true });
const rows = [
{
id: "p1",
slug: "learning-notebook",
name: "Learning notebook",
price: 24900,
category: "stationery",
description: "A notebook for diagrams and project notes.",
stock: 20,
active: true,
},
{
id: "p2",
slug: "desk-lamp",
name: "Desk lamp",
price: 89900,
category: "desk",
description: "Light up your practice workspace.",
stock: 10,
active: true,
},
{
id: "p3",
slug: "pen-set",
name: "Pen set",
price: 9900,
category: "stationery",
description: "Three pens for everyday learning.",
stock: 30,
active: true,
},
];
for (const product of rows)
await products.updateOne(
{ id: product.id },
{ $setOnInsert: product },
{ upsert: true },
);
console.log("Learning products seeded; existing records preserved.");
} finally {
await client.close();
}
This isolates MongoDB product access from the storefront’s components.
import "server-only";
import { db } from "./db";
import type { Product } from "./products";
export type StoreProduct = Product & { stock: number; active: boolean };
export const inventory = db.collection<StoreProduct>("products");
export async function getProducts() {
const rows = await inventory
.find({ active: true })
.sort({ name: 1 })
.limit(100)
.toArray();
return rows.map(({ _id, ...product }) => {
void _id;
return product;
});
}
export async function getProduct(slug: string) {
const row = await inventory.findOne({ slug, active: true });
if (!row) return null;
const { _id, ...product } = row;
void _id;
return product;
}
This page owns collection-level loading and renders one reusable card per resulting product.
import { getProducts } from "@/lib/store";
export const dynamic = "force-dynamic";
import ProductCard from "@/components/product-card";
type Query = { q?: string | string[]; sort?: string | string[] };
export default async function ProductsPage({
searchParams,
}: {
searchParams: Promise<Query>;
}) {
const products = await getProducts();
const query = await searchParams;
const q = typeof query.q === "string" ? query.q.trim().slice(0, 100) : "";
const sort = query.sort === "price" ? "price" : "name";
const visible = products
.filter((p) => p.name.toLowerCase().includes(q.toLowerCase()))
.sort((a, b) =>
sort === "price" ? a.price - b.price : a.name.localeCompare(b.name),
);
return (
<>
<h1>Products</h1>
<form action="/products" method="get">
<label>
Search <input name="q" defaultValue={q} maxLength={100} />
</label>
<label>
Sort{" "}
<select name="sort" defaultValue={sort}>
<option value="name">Name</option>
<option value="price">Price: low to high</option>
</select>
</label>
<button>Apply</button>
</form>
<p>{visible.length} products</p>
<div className="grid">
{visible.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
{visible.length === 0 && <p>No matches. Try another search.</p>}
</>
);
}
This one page handles all product-detail URLs by resolving the requested slug.
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getProduct } from "@/lib/store";
import { money } from "@/lib/money";
import AddToCart from "@/components/add-to-cart";
export const dynamic = "force-dynamic";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const product = await getProduct(slug);
return { title: product?.name ?? "Product not found" };
}
export default async function ProductPage({ params }: Props) {
const { slug } = await params;
const product = await getProduct(slug);
if (!product) notFound();
return (
<>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>{money(product.price)}</p>
<p>{product.stock} available</p>
{product.stock > 0 ? <AddToCart id={product.id} /> : <p>Out of stock</p>}
</>
);
}
This combines server-supplied catalog facts with browser-owned cart quantities.
"use client";
import type { Product } from "@/lib/products";
import { money } from "@/lib/money";
import { useCart } from "@/components/cart-provider";
export default function CartContents({ products }: { products: Product[] }) {
const { lines, ready, setQuantity, clear } = useCart();
if (!ready) return <p>Restoring cart…</p>;
const total = lines.reduce(
(sum, line) =>
sum +
(products.find((p) => p.id === line.productId)?.price ?? 0) *
line.quantity,
0,
);
return (
<>
<h1>Your cart</h1>
{lines.map((line) => {
const product = products.find((p) => p.id === line.productId);
return (
<article key={line.productId}>
<h2>{product?.name ?? "Unavailable product"}</h2>
<label>
Quantity{" "}
<input
type="number"
min="1"
max="10"
value={line.quantity}
onChange={(e) => {
const n = Number(e.target.value);
if (Number.isInteger(n) && n > 0)
setQuantity(line.productId, n);
}}
/>
</label>
<p>{money((product?.price ?? 0) * line.quantity)}</p>
<button onClick={() => setQuantity(line.productId, 0)}>
Remove
</button>
</article>
);
})}
{!lines.length && (
<p>Your cart is empty. Visit Products to add an item.</p>
)}
<p>Total: {money(total)}</p>
{!!lines.length && <button onClick={clear}>Clear cart</button>}
</>
);
}
This server page supplies current catalog facts to the interactive cart.
import { getProducts } from "@/lib/store";
import CartContents from "@/components/cart-contents";
export const dynamic = "force-dynamic";
export default async function CartPage() {
return <CartContents products={await getProducts()} />;
}
This keeps one cart provider above all of the store’s consumers.
import type { ReactNode } from "react";
import Link from "next/link";
import { CartProvider } from "@/components/cart-provider";
import CartLink from "@/components/cart-link";
import "./globals.css";
export const metadata = {
title: "EduShop",
description: "My Next.js learning project",
};
export default function Layout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<CartProvider>
<nav>
<Link href="/">Home</Link>
<Link href="/products">Products</Link>
<CartLink />
<Link href="/account">Account</Link>
</nav>
<main>{children}</main>
</CartProvider>
</body>
</html>
);
}
Change the notebook price using the learning database, rerun the seed command, and reload /products.
The edited price remains; the seed does not overwrite it.
The upsert matches the existing ID and $setOnInsert has no effect on that existing record.
Use the store database, not the task database. Set the correct MongoDB URI and DB name before running seed.
Likely cause: Products were not seeded into the database selected by the web app.
Check and correct: Check MONGODB_DB in .env.local and run the seed command from the store folder.
Likely cause: A component still imports the original products array at runtime.
Check and correct: Use the server-loaded product props in CartContents and getProducts/getProduct in public product pages.
Add a signed-in customer name to the account navigation while preserving server-side session reads.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
Its input contract is a plain product object. Storage details are handled before the object reaches the card.
No. This version retains device-local cart state. Account cart storage and merging require separate data operations and an explicit policy.