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
Customers should browse products, while administrators may change them. A different screen is not enough to enforce that distinction. We add a server-managed permission and check it at both the page and mutation boundaries.
An administrator is still an authenticated user, with an extra permission stored on the server. Never allow a registration form or a browser field to grant that permission.
For this learning app, a local script grants access to one existing test account. There is no public role-changing endpoint. Every admin page and write checks the role again.
Uncheck Visible in store to archive a product rather than deleting its history. This small lab lists up to 100 products; pagination is a follow-up exercise.
Represent a role without trusting account input
storeRoles maps a verified user ID to an admin role. requireAdmin first requires an authenticated user, then looks for that user’s administrator assignment. A customer session alone does not satisfy that lookup.
The make-admin script is a local operator action for this lab. It finds an existing auth user by email and writes the corresponding role. There is no registration checkbox or public endpoint that lets a visitor become an administrator. Run it only for your intended learning account.
Read an admin form as an input contract
The product form accepts editable fields: name, slug, category, description, price, stock and visibility. It supplies an ID for an existing product, while a new product gets a server-generated ID. That ID should remain stable even when the product name changes.
The action normalizes text, validates a URL-safe slug, and checks numeric ranges. Number alone is not sufficient validation: Number("") is zero, and fractions can be produced from text. The example checks nonempty numeric input and integer ranges before saving.
Price is expressed in paise in both the label and validation. Stock is an integer count, not a currency amount. Keeping those units explicit prevents a valid-looking number from meaning the wrong thing.
Create, edit and archive deliberately
For creation, insertOne stores a new record with a generated ID. For editing, updateOne targets the existing public ID and applies $set. A missing edited product returns an error rather than being silently inserted. Unique database indexes reject duplicate slugs even if concurrent requests race.
Unchecking Visible in store stores active=false. Public reads filter active products, so the catalog hides the record and a details lookup returns missing. We retain the record rather than destroying references to it. Future order history stores its own name and price snapshot as well.
An absolute stock edit replaces the current stock count. This simple admin lab is best used without concurrent inventory adjustments. In a busy store, use audited stock adjustments or version checks so an administrator’s stale form cannot overwrite a checkout deduction.
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 admin page verifies the session and role before reading management data.
2
An administrator submits normalized product fields.
3
The action verifies the role again, validates fields and writes the product.
4
Revalidation updates the storefront and admin views; inactive records no longer appear publicly.
Compare a customer request with an admin request
A customer submits a valid-looking product form with price=1. requireAdmin runs before any product write.
The role lookup has no match, so the action stops. Input validity does not grant permission.
An administrator submits price=24900 and stock=20. The role and field checks pass.
The saved product represents ₹249.00 with twenty available units, and public cards use that updated data.
3. Build it, one file at a time
Add the role checker, promotion script, product form, action and admin page.
Register a test account, then run the make-admin command with that account’s actual email.
Open /admin. Create a product, edit its price and stock, then archive it. Test /admin with a normal customer account.
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.
lib/admin.ts
This checks an additional store-management permission after verifying identity.
lib/admin.ts
import "server-only";
import { db } from "./db";
import { requireUser } from "./session";
import { notFound } from "next/navigation";
export async function requireAdmin() {
const user = await requireUser();
const role = await db
.collection("storeRoles")
.findOne({ userId: user.id, role: "admin" });
if (!role) notFound();
return user;
}
Read the code
requireUser establishes who is calling. A server-side storeRoles lookup decides whether that user has role=admin.
No match stops the operation with notFound. The return value is the verified user only after both checks pass.
Pages and mutation functions call this helper separately. Protecting only a link or navigation menu is not sufficient.
scripts/make-admin.mjs
This local operator script grants the administrator role to an existing learning account.
scripts/make-admin.mjs
import { MongoClient } from "mongodb";
const email = process.argv[2];
if (!email)
throw new Error(
"Usage: node --env-file=.env.local scripts/make-admin.mjs your-test-email",
);
const client = new MongoClient(process.env.MONGODB_URI);
try {
const db = client.db(process.env.MONGODB_DB);
const user = await db
.collection("user")
.findOne({ email: email.toLowerCase() });
if (!user) throw new Error("Create the test account through /sign-in first.");
await db
.collection("storeRoles")
.createIndex({ userId: 1 }, { unique: true });
await db
.collection("storeRoles")
.updateOne(
{ userId: user._id.toString() },
{ $set: { role: "admin" } },
{ upsert: true },
);
console.log("Learning account is now a store administrator.");
} finally {
await client.close();
}
Read the code
The email argument selects an auth user in the configured database. The script does not create a password or a new account.
The stored user ID is written to a separate role collection with a unique userId index. The update is repeatable for the same account.
There is no public HTTP route for this operation. Run it deliberately for your test administrator and keep normal customers unprivileged.
app/admin/actions.ts
This is the server-side boundary for both creating and editing products.
app/admin/actions.ts
"use server";
import { randomUUID } from "node:crypto";
import { revalidatePath } from "next/cache";
import { requireAdmin } from "@/lib/admin";
import { inventory } from "@/lib/store";
export type Result = { message: string };
export async function saveProduct(
_previous: Result,
data: FormData,
): Promise<Result> {
await requireAdmin();
const id = String(data.get("id") ?? "");
const name = String(data.get("name") ?? "").trim();
const slug = String(data.get("slug") ?? "").trim();
const category = String(data.get("category") ?? "").trim();
const description = String(data.get("description") ?? "").trim();
const priceText = String(data.get("price") ?? "");
const stockText = String(data.get("stock") ?? "");
const price = Number(priceText);
const stock = Number(stockText);
if (
!name ||
name.length > 100 ||
!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) ||
slug.length > 100 ||
!category ||
category.length > 60 ||
description.length > 1000 ||
!priceText ||
!stockText ||
!Number.isSafeInteger(price) ||
price < 1 ||
price > 10000000 ||
!Number.isInteger(stock) ||
stock < 0 ||
stock > 100000
)
return {
message:
"Check all fields. Price must be positive integer paise; stock must be a non-negative integer.",
};
const changes = {
name,
slug,
category,
description,
price,
stock,
active: data.get("active") === "on",
};
try {
if (id) {
const result = await inventory.updateOne({ id }, { $set: changes });
if (!result.matchedCount) return { message: "Product not found." };
} else {
await inventory.insertOne({ id: randomUUID(), ...changes });
}
} catch {
return {
message:
"Could not save. Check for a duplicate slug or a connection problem.",
};
}
revalidatePath("/", "layout");
return { message: "Product saved." };
}
Read the code
requireAdmin executes before accepting a write. The action then reads only its intended fields rather than spreading FormData into a document.
Text lengths, slug shape, integer paise and stock ranges are validated. Empty numeric text is checked explicitly because Number("") would otherwise look like zero.
A supplied ID targets an update with a matchedCount check. Creation generates a new ID. Duplicate-slug or database failures return feedback; successful writes revalidate shared route output.
components/product-form.tsx
This reuses one form for product creation and editing while leaving authorization to the server.
The page calls requireAdmin before querying the full inventory, including inactive products.
An empty ProductForm creates a product. Existing rows are converted to plain props for edit forms, discarding MongoDB _id.
The key includes the saved product values to refresh uncontrolled form defaults after a successful edit. The list cap keeps the beginner example bounded; pagination is a later extension.
4. Run it and check your result
An administrator can create and edit a product.
An archived product disappears from the public catalog.
A customer cannot open /admin or successfully invoke its save action.
5. Predict, change and observe
Archive the notebook while a guest cart still contains p1. Visit its old details URL and then the cart.
Compare your prediction with the expected result
What you should observe
The details page is missing and the cart flags the unavailable product.
Why it happens
Archiving affects catalog availability but does not remotely erase a browser’s stored choices. Checkout must recheck availability before accepting them.
6. Troubleshoot with evidence
A common mistake
A hidden Admin link is not authorization. Also, ₹249 is stored as 24900 paise, not 249.
An intended admin account still cannot open /admin.
Likely cause: The role was created for another database or identity.
Check and correct: Register the learning account first, then run make-admin against the same store database and actual account email.
A product cannot be saved with an existing slug.
Likely cause: The database uniqueness rule rejects the duplicate.
Check and correct: Choose a different slug or edit the existing product. Do not remove the unique index to bypass the rule.
7. Practice and explain it back
Your independent task
Add a low-stock filter, and retain requireAdmin in every new admin operation.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
Why does the action check requireAdmin when the page already did?
The action is a separate request boundary. A caller may submit it without loading the page, and permissions may change between requests.
Why archive instead of deleting?
It removes public availability while retaining the product record and stable identity. Historical references remain easier to explain and manage.