Skip to lesson content

PROJECT 6 · LESSON 16 OF 18

Move the store to a database

Resume EduShop, replace file reads and add customer accounts.

  • data access
  • seeding
  • reuse
  • customer sessions

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Keep the two project histories separate

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.

Replace imported values with asynchronous reads

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.

Seed once without destroying later edits

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.

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. A product route calls the server-only store data module.

  2. MongoDB returns active product records.

  3. The data module returns plain product values to the page.

  4. Existing cards and interactive cart consumers render those values; auth separately identifies customers when required.

Trace one unchanged card through the migration

  1. Before migration, p1 came from the exported products array. After migration, the seeded document has the same id and slug.
  2. The card still receives name, price and description as props and builds the same URL.
  3. The cart’s saved p1 selection can still resolve because the public ID stayed stable.
  4. If you had replaced public IDs without a migration, restored cart lines could no longer identify their products.

3. Build it, one file at a time

  1. Replace package.json, add the environment file, database and auth modules below, then run npm install. Keep .env.local out of Git.
  2. Run the seed command once after configuring .env.local. It creates unique product indexes and inserts starter products without overwriting edits.
  3. Replace the catalog, detail and cart pages. Open /sign-in to register a customer, then visit /account.
Terminal
npm install
node --env-file=.env.local scripts/seed.mjs
npm run dev

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.

package.json

This is the project’s dependency and command manifest. It tells npm what to install and how to run the learner application.

package.json
{
  "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"
  }
}

Read the code

  1. dependencies lists packages needed by the application; devDependencies lists development tools and TypeScript definitions. Install from the folder containing this file.
  2. scripts.dev runs the development server; scripts.build prepares production output; scripts.start serves that output. typecheck checks TypeScript without emitting JavaScript.
  3. When a later lesson replaces this file to add database or auth packages, run npm install again. Keep your generated package-lock.json so subsequent installs use a consistent resolution.

lib/db.ts

This creates and shares the server-side database client and selects the learning database.

lib/db.ts
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");

Read the code

  1. import server-only prevents this runtime module from being pulled into a Client Component. The URI stays in server configuration.
  2. The explicit missing-URI check produces an actionable configuration error. MongoClient is reused during development to avoid creating clients on every hot reload.
  3. client.db selects the configured database. Collection and query modules use this handle; pages should not rebuild the connection themselves.

lib/auth.ts

This configures the server authentication provider and its persistent storage adapter.

lib/auth.ts
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 },
});

Read the code

  1. mongodbAdapter reuses the learning database and client. Auth data is stored in provider collections rather than mixed into task documents.
  2. emailAndPassword enables the account method used by the forms. The provider handles password verification and sessions.
  3. The base URL and secret come from server environment variables. Never import this runtime module into an interactive credential form.

lib/auth-client.ts

This creates the browser-facing auth helper used by sign-in and sign-out controls.

lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();

Read the code

  1. createAuthClient from better-auth/react exposes methods that communicate with the configured provider endpoints.
  2. With the default same-origin setup, the browser uses this application’s auth route. No database URI or server secret is passed to this helper.

lib/session.ts

This provides one server-side way to require the current request’s authenticated user.

lib/session.ts
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;
}

Read the code

  1. await headers() reads the incoming request context and getSession asks the provider to verify it.
  2. If there is no session, redirect interrupts the current operation and points to /sign-in. Code after that branch assumes an authenticated user.
  3. Returning session.user gives callers a trusted identity source. The caller must still enforce ownership or administrator permissions as appropriate.

app/api/auth/[...all]/route.ts

This mounts the auth provider’s HTTP interface inside the App Router.

app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);

Read the code

  1. The catch-all folder captures multiple /api/auth/... paths handled by the provider. It does not create a rendered page.
  2. toNextJsHandler adapts the configured auth instance, and the named GET and POST exports tell Next.js which request methods it handles.

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.

.env.example

This is a list of configuration names and placeholder values to copy into .env.local.

.env.example
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

Read the code

  1. MONGODB_URI supplies the database connection and MONGODB_DB selects the learning database. The application and standalone scripts must agree on both.
  2. Where present, BETTER_AUTH_URL is the browser origin and BETTER_AUTH_SECRET must be replaced with a high-entropy secret. Neither value is a user account password.
  3. Do not rename secrets with a NEXT_PUBLIC_ prefix. Keep the completed .env.local private and restart the server after changing it.

scripts/seed.mjs

This initializes the learning store’s product records and uniqueness constraints.

scripts/seed.mjs
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();
}

Read the code

  1. The script runs under Node with --env-file=.env.local. It does not receive Next.js environment loading automatically.
  2. Unique indexes on id and slug prevent ambiguous product identity. updateOne with upsert and $setOnInsert creates missing starters but preserves existing edits.
  3. finally closes the script’s client so the one-off process can finish cleanly. Check the database name before running it.

lib/store.ts

This isolates MongoDB product access from the storefront’s components.

lib/store.ts
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;
}

Read the code

  1. StoreProduct extends the existing product shape with stock and active. The collection handle is server-only.
  2. Public list and details queries require active=true. The list is sorted and capped at 100 records for this lab.
  3. The MongoDB _id is removed before returning product props. The public id remains stable for cart references. The unused _id binding is intentionally discarded.

app/products/page.tsx

This page owns collection-level loading and renders one reusable card per resulting product.

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

Read the code

  1. getProducts now awaits the server database module. The page keeps the existing search and presentation contract while replacing its data source.
  2. map creates ProductCard elements, each with one product prop and a stable id key. ProductCard does not fetch its own list.
  3. Await searchParams, normalize q to a bounded string and accept only supported sort values. A GET form writes those selections back into the URL.
  4. filter creates a new array; sort rearranges that copy. The count and empty message are derived from the same visible array used for cards.

app/products/[slug]/page.tsx

This one page handles all product-detail URLs by resolving the requested slug.

app/products/[slug]/page.tsx
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>}
    </>
  );
}

Read the code

  1. Props declares asynchronous params. Await it before extracting slug; [slug] matches the segment but does not prove a product exists.
  2. generateMetadata supplies the document title independently of the visible page heading.
  3. The page checks its lookup result before reading fields. notFound stops the success branch and selects the segment’s fallback UI.
  4. getProduct reads active database records. The stock check controls the add button, while checkout still checks current stock again.

components/cart-contents.tsx

This combines server-supplied catalog facts with browser-owned cart quantities.

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

Read the code

  1. products arrives as plain serializable props. useCart supplies the current line IDs and quantities.
  2. The ready branch distinguishes initial restoration from an empty cart. Each line then looks up the current product by ID.
  3. Quantity input events validate an integer before requesting a state change. Missing product information is labelled unavailable; checkout must reject it rather than accept the zero-price display fallback.

app/cart/page.tsx

This server page supplies current catalog facts to the interactive cart.

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

Read the code

  1. getProducts runs in the server-only data layer and returns plain values for CartContents.
  2. CartContents owns browser interactions through the provider; the page does not read localStorage.
  3. The route is dynamic so visits can read current catalog data.

app/layout.tsx

This keeps one cart provider above all of the store’s consumers.

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

Read the code

  1. The root layout remains a Server Component and wraps navigation and children in CartProvider.
  2. CartLink consumes shared state, while ordinary Links navigate between routes. The provider owns the interactive state; the layout still owns the document.
  3. Passing children through a client provider does not require importing all server page modules into that client module. Preserve this composition boundary.

4. Run it and check your result

  • Changing a product name in the learning database changes the catalog.
  • The same ProductCard renders database-backed products.
  • A customer can sign up, sign in and sign out.

5. Predict, change and observe

Change the notebook price using the learning database, rerun the seed command, and reload /products.

Compare your prediction with the expected result

What you should observe

The edited price remains; the seed does not overwrite it.

Why it happens

The upsert matches the existing ID and $setOnInsert has no effect on that existing record.

6. Troubleshoot with evidence

A common mistake

Use the store database, not the task database. Set the correct MongoDB URI and DB name before running seed.

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.

The cart still displays the old file-backed prices.

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.

7. Practice and explain it back

Your independent task

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.

Why can ProductCard stay unchanged?

Its input contract is a plain product object. Storage details are handled before the object reaches the card.

Does customer login save the guest cart to the account?

No. This version retains device-local cart state. Account cart storage and merging require separate data operations and an explicit policy.