Back to projectsesc fig. 01 — the trailer
trailer2:16tests108 green
LiveLead developer108 tests

Rep Theory

A concept e-commerce store for lifting gear and 12-week training programs. I built it end to end over three assignments, then wrote the tests that try to break it.

108automated tests, every push
Asecurity headers grade
3test payments in one session
$0real money moved
ROLELead developer · full stack
TEAM3 Laurier CS students · I built every feature
COURSECP340-B · E-commerce
TIMELINEOct – Nov 2026 · 6 PRs
STACKNext.js 16 · React 19 · TypeScript · Tailwind 4
SERVICESStripe (test) · Upstash Redis · Vercel · GA4
scroll ↓
01 / the product

Gear and programs for the last rep

Rep Theory sells lifting gear (straps, wraps, cable attachments, clips) and 12-week training programs, plus a monthly 1:1 coaching subscription. It isn’t a real brand: checkout runs in Stripe test mode and nothing ships.

  • →Gear pages draw the product in code: a blueprint SVG that updates live as you pick a colour, a size or the text stitched on it.
  • →Programs show the 12-week block, sample weeks whose gear tags link to products, and a plan comparison.
  • →A journal with topic filters kept in the URL, scroll-spy contents and share links.
  • →Assignment 3 added engagement: live chat, reviews, recommendations and consent-gated analytics.
6gear products
312-week programs
1coaching subscription
What I builtAll of it, as lead developer: the storefront, cart and Stripe checkout, the journal and SEO, every Assignment 3 feature, the 108-test suite and the CI pipeline. My two teammates handled the security configuration (2FA, firewall), the analytics write-up, supplier research and the reports.
02 / architecture

Static first. Server only where it counts.

Every page is pre-rendered at build time and served from Vercel’s CDN. Server code runs in only four places: checkout, the paid-order page, reviews and contact. Everything else (cart, consent, recently viewed) lives in the visitor’s browser.

Next.js 16App Router; generateStaticParams pre-builds every product and post pageStripeHosted Checkout: card details never touch our pages, and Stripe is the record of paymentUpstash RedisAdded in A3 for reviews, messages and rate limits; serverless-friendly, pay per requestlocalStorageCart, cookie choice and history, synced across tabs with useSyncExternalStoreGitHub ActionsLint, types, unit and browser tests on every push and pull request
Why no database for the shop?The catalogue is code and Stripe already stores every order, so a database would have been one more thing to secure and keep in sync. Redis arrived only when there was data that really belongs to the store: reviews and messages.
03 / checkout

A checkout that ends in Stripe’s own record

The cart sends only slug, qty and options. The server checks the origin and rate limit, re-prices every line, and creates one Checkout Session with gear, programs and a monthly coaching subscription in the same cart.

  • →Shipping and HST are their own Stripe lines, so Stripe’s receipt matches our cart to the cent.
  • →Coaching makes the session mode: subscription, and its tax is a separate recurring line.
  • →Order numbers like RT-2026-4F8K2 skip look-alike characters (0/O, 1/I).
  • →The confirmation page reads the session back from Stripe: order number, email, ship-to, card ending. It never trusts the redirect URL.
3test payments in the A3 session
$284.74CAD processed (test mode)
$94.91average order
Stripe test-mode dashboard: three successful payments on Nov 29, 2026
src/lib/stripe.tsserver-only
5export function getStripe() {
6 const key = process.env.STRIPE_SECRET_KEY;
7 if (!key) throw new Error("STRIPE_SECRET_KEY is not set");
8 if (!key.startsWith("sk_test_")) {
9 // This is a student project: refuse to run against a live account
10 throw new Error("Only Stripe test keys (sk_test_…) are allowed");
04 / never trust the browser

The browser sends what you picked, never what it costs

A cart in localStorage is just user input: anyone can open DevTools and post their own. So the server treats every line as hostile and rebuilds it from the catalogue.

  • →Unknown product, colour or option → the line is dropped, not trusted.
  • →Quantity must be a whole number ≥ 1, capped at 10; coaching at 1.
  • →A price field in the request is simply never read.
  • →Embroidery text is upper-cased to A–Z, 0–9 and spaces, 12 characters max.
src/lib/pricing.tsreturns null → dropped
68export function validateLine(raw: unknown): CartLine | null {
69 if (!raw || typeof raw !== "object") return null;
70 const r = raw as Record<string, unknown>;
71 if (typeof r.slug !== "string") return null;
72 const found = getProduct(r.slug);
73 if (!found) return null;
74 const p = found.product;
75 const kind = kindOf(p);
76
77 const qtyNum = Number(r.qty);
78 if (!Number.isInteger(qtyNum) || qtyNum < 1) return null;
79 const qty = kind === "coaching" ? 1 : Math.min(qtyNum, MAX_QTY);
tests/unit/pricing.test.tsthe attack, as a test
81it("ignores a price sent by the browser", () => {
82 const l = validateLine({ slug: "barbell-clips", qty: 1, colour: "Black", price: 0.01 });
83 expect(priceCart([l!]).subtotalCents).toBe(2400);
84});
05 / pricing engine

One pricing engine, two runtimes

lib/pricing.ts runs in the browser to show the live cart and on the server to charge it, so the two can’t disagree. All money is integer cents, so there’s no floating-point drift.

  • →$9.99 shipping on gear, free once gear reaches $75; programs and coaching never ship.
  • →13% Ontario HST on subtotal + shipping, rounded once.
  • →One coaching subscription per order, shown as its own monthly line with its own tax.
13%tax rate (Ontario HST)
$75free-shipping threshold
$84.74Playwright-checked total for one lat bar
src/lib/pricing.ts
136 const gearCents = lines
137 .filter((l) => l.kind === "gear")
138 .reduce((s, l) => s + l.totalCents, 0);
139 const hasGear = gearCents > 0;
140 const subtotalCents = lines.reduce((s, l) => s + l.totalCents, 0);
141 const shippingCents =
142 !hasGear || gearCents >= FREE_SHIPPING_OVER_CENTS ? 0 : SHIPPING_CENTS;
143 const taxCents = tax(subtotalCents + shippingCents);
A test that checks real moneyThe Playwright suite adds a $65 lat bar and expects exactly $9.99 shipping and $84.74 due: $74.99, plus $9.75 HST. If the shipping rule or the rounding ever changes, CI goes red.
06 / one source of truth

Add a product in one place

data/catalog.ts is the single source of truth. Each entry generates its card, its detail page, its related links and its program-week gear tags. In Assignment 3, four new features read from the same file instead of copying it.

  • →Pricing, recommendations, the chat greeting and the reviews API all look products up by slug.
  • →generateStaticParams turns 10 entries into 10 static pages at build time.
  • →Unknown slugs 404 everywhere: a page, a review, a checkout line.
10catalogue entries
24modules import it
0copies of a price anywhere else
07 / live chat

Instant answers, and a person when it can’t help

The Ask us button opens a chat on every page. It greets you by the product you’re looking at, answers common questions instantly from what’s already on the site, and hands anything else to the team as a ticket with an instant auto-reply.

  • →Order matters: “Can I return my straps?” mentions straps, but returns need a person, so the NEEDS_PERSON check runs before topic keywords.
  • →Logic lives outside the widget in lib/chat.ts, a pure function with 11 unit tests, while the React component only renders.
  • →Keyboard-friendly: Escape closes it and focus stays inside, both checked by Playwright.
src/lib/chat.ts
71export function matchAnswer(question: string, chipId?: string): { id: string; answer: Answer } {
72 if (chipId) {
73 const hit = ANSWERS.find((a) => a.id === chipId);
74 if (hit) return { id: hit.id, answer: hit.answer };
75 }
76 if (NEEDS_PERSON.test(question)) {
77 const human = ANSWERS.find((a) => a.id === "human")!;
78 return { id: human.id, answer: human.answer };
79 }
80 const hit = ANSWERS.find((a) => a.keys.test(question));
81 return hit ? { id: hit.id, answer: hit.answer } : { id: "unknown", answer: FALLBACK };
08 / reviews + contact

Every request runs the gauntlet

Reviews and messages are the first data strangers can write to the store, so /api/reviews and /api/contact check each request in a fixed order and fail with the right status code, not just an error.

CodeWhen
403Posted from another website (the Origin header doesn’t match): a basic CSRF check201*A bot filled the hidden “website” field: it gets a fake success and nothing is saved422Field errors, one per field, so the form can highlight exactly what’s wrong503Redis isn’t configured: “offline, email us instead”, while the rest of the site still works4293 reviews or 3 messages per visitor per 10 minutes, with a Retry-After header
src/app/api/reviews/route.tsafter the 403 + 400 checks
52 // Honeypot: real people never see or fill this field
53 if (typeof body.website === "string" && body.website.trim() !== "") {
54 return NextResponse.json({ ok: true }, { status: 201 });
55 }
Tested without a databaseThe 17 API tests swap Redis for a tiny in-memory fake through vi.mock, so each status code is checked in milliseconds, with no network and no keys. Every request also gets its own fake IP, so one test’s rate limit can’t leak into the next.
09 / recommendations

Recommended, and it tells you why

“Recommended for you” scores every product against what you’ve viewed, entirely in your browser. Your history never leaves localStorage, and one click clears it.

  • →+3 when a viewed product lists it as related, +1 for the same category.
  • →Recency matters: each view is weighted 1, ½, ⅓… newest first.
  • →Never recommends the page you’re on, something you’ve viewed, or anything in your cart.
  • →New visitors get team picks, so the section is never empty, and the top pick says “because you viewed…”.
5.0top score: Figure-8 Straps
3picks shown
0requests to a server
src/lib/recommend.ts
17 viewed.forEach((slug, rank) => {
18 const found = getProduct(slug);
19 if (!found) return;
20 const weight = 1 / (rank + 1);
21 for (const rel of found.product.related ?? []) {
22 const cur = scores.get(rel) ?? { score: 0 };
23 cur.score += 3 * weight;
Next step: real dataThis is a rule-based recommender, explainable and testable. The analytics now record view_item and add_to_cart, so the next step is an “also bought” model learned from real orders, measured against these rules before it replaces them.
10 / analytics

Analytics that wait for a yes

Google Analytics 4 doesn’t load at all until a visitor accepts analytics cookies. Decline, or withdraw later, and its cookies are deleted. Vercel Web Analytics is cookieless and counts everyone.

  • →Shop events (view_item, add_to_cart, begin_checkout, purchase) are queued if GA is still starting, then flushed, so the first page view isn’t lost.
  • →The Content Security Policy only allows Google’s script host, the one exception to “our scripts only”.
31page views, 4 consented users
7 → 6product views → add to cart
3purchases
What the data saidTesters explored (7.8 pages each), but no program page made the top five, even though programs are the highest-margin, zero-shipping products. Action: give programs a stronger spot on the home page and in recommendations. Every order cleared the $75 free-shipping bar.
tests/e2e/security-privacy.spec.ts
22test("Google Analytics only loads after the visitor accepts", async ({ page }) => {
23 await blockGoogle(page);
24 await page.goto("/");
25 const gaScript = page.locator('script[src*="googletagmanager.com/gtag/js"]');
26 await expect(page.getByRole("region", { name: "Cookie choices" })).toBeVisible();
27 await expect(gaScript).toHaveCount(0);
28
29 await page.getByRole("button", { name: /accept all/i }).click();
30 await expect(gaScript).toHaveCount(1);
11 / security

Secure by default, and proven by tests

Security is layers, each assuming the last one failed: HTTPS everywhere, strict headers, origin checks, honeypots, rate limits, server-side pricing, and card data that never touches our servers.

Asecurity headers grade
12requests the firewall denied in a day
10checkout attempts per visitor per minute
SSL + HSTSHTTPS forced for two years, preloadedCSPOnly our scripts and styles; Google only after consent; no framing, no pluginsRate limitsSliding windows in Redis, separate per feature, so spamming reviews can’t block checkoutCard testing10 checkout attempts a minute stops scripts trying stolen cards2FA + firewallOn GitHub, Vercel and Stripe (set up by Ronnie); Vercel Firewall with DDoS mitigation
tests/e2e/security-privacy.spec.tsone test per endpoint
15for (const path of ["/api/reviews", "/api/contact", "/api/checkout"]) {
16 test(`${path} rejects posts from other websites`, async ({ request }) => {
17 const res = await request.post(path, { headers: { origin: "https://evil.example" }, data: {} });
18 expect(res.status()).toBe(403);
12 / testing

108 tests, aimed at what would hurt

Two layers. Fast unit and API tests check the rules; browser tests check that a real visitor can actually use them, at desktop and phone width.

Vitest · 69Pricing, tax and free shipping; tampered carts; input cleaning and link spam; rate limiting; every API status code against a fake Redis; recommendations; chat routingPlaywright · 39Every page loads with no errors and no sideways scroll (desktop + Pixel 7); cart totals; chat, reviews and contact flows; security headers; consent gates GA; cross-site posts rejected
  • →Runs against a production build (next build && next start), the same code visitors get.
  • →No secrets needed: reviews and contact are mocked in the browser with page.route, and Google is blocked, so tests never touch real services.
  • →Each test owns its state: cookies are pre-declined through an init script, so the banner never covers what a test clicks.
  • →Attacks are tests: a price of $0.01, a cross-site post, analytics before consent. Each one is a test that would fail if the protection broke.
13 / ci + a flaky test

Nothing merges red, and red has to mean something

.github/workflows/ci.yml runs the whole suite on every push and pull request. A newer push cancels the older run, and a failed run uploads the Playwright report so the failure can be replayed.

7CI steps
20commits
6pull requests merged
The flaky testAfter the A3 merge, CI went red once and passed on a re-run. Running the suspect test 10 times locally, it failed once. Cause: the test left the product page before React hydrated and saved the view, so “Recommended for you” never appeared. Fix: wait for the view to land in localStorage. After the fix, 20 out of 20 runs passed.
tests/e2e/shop.spec.tsthe fix
27 await page.goto("/equipment/neutral-grip-lat-bar");
28 // the view is recorded after hydration; don't navigate away before it lands
29 await expect.poll(() => page.evaluate(() => localStorage.getItem("rt-viewed")))
30 .toContain("neutral-grip-lat-bar");
31 await page.goto("/");
14 / engineering principles

The principles, and where they live in the code

Most of the work here is invisible to a shopper. These are the rules I kept to, each tied to the file that enforces it:

PrincipleIn practice
Never trust the clientPrices, options and quantities are rebuilt on the server (pricing.ts)Single source of truthOne catalogue feeds pages, pricing, chat, reviews and recommendationsDRY across runtimesThe same pricing module runs in the cart and in checkoutSeparation of concernsPure logic (chat, recommend, pricing) apart from React, so it’s unit-testableDefence in depthOrigin → JSON → honeypot → validation → limits, before anything is savedGraceful degradationNo Redis? Reviews say “offline”, contact points to email, the site still buildsLeast privilegeTest keys only; server-only imports keep secrets out of the browser bundlePrivacy by designOptional cookies off by default; browsing history never leaves the deviceTest pyramid + CIMany fast unit tests, fewer browser tests, all on every push
15 / every screen, every visitor

Built for phones, keyboards and the planet

The Playwright smoke test loads all 11 key pages on a Pixel 7 and fails if anything scrolls sideways. Drawers trap focus and close with Escape, toggles expose their state to screen readers, and every animation respects reduced motion.

  • →Sustainability page (A3): digital-first programs, fewer and fuller parcels, plastic-free packaging, and three real eco suppliers, each linked with rel="noopener" (checked by a test).
  • →Skip link, visible focus and aria states on accordions and toggles.
11pages checked at phone width
≤ 1pixels of sideways scroll allowed
3eco suppliers, linked
16 / reflection + what’s next

From “I want to break it” to breaking it in CI

After Assignment 2 I wrote that the hard part of e-commerce is everything the customer never sees, and that next I wanted to break the store on purpose. In Assignment 3 I did: tampered prices, cross-site posts, bots, floods and analytics before consent are now tests that run on every push.

The lesson I’ll keep is that a test is only worth something if red means something. A flaky test teaches everyone to click re-run. Finding the 1-in-10 failure and fixing its cause taught me more about React hydration than any feature did.

Next is the ML side. With view_item and add_to_cart now flowing into analytics, I want to train an “also bought” recommender on real orders and measure it against today’s explainable rules before it ever reaches the live store.