Why this matters
Every number, approval button, and error message a store owner sees passes through the frontend, so a careless screen can erase months of backend security and math discipline in one glance. When an overview screen grew to 8,872 pixels tall, founders scrolled past 76 expanded technical panels just to check daily spend; when browser code misread a real cookie session as offline preview, a signed-in user saw stamped sample numbers and even a fabricated disconnect receipt. The frontend rules here exist to prevent those exact failures: keep browser bundles lean and secret-free, never disguise an API error as sample data, lock every pixel into a closed 58-part kit, write calm Turkish-first copy, and make every screen work at 320 pixels, by keyboard, with screen readers, and on monochrome paper.
The ideas
1. Next.js App Router, Server Components, hydration, and workspace routes
A web app splits work between our Node.js server and the visitor's browser. In the Next.js App Router, folders under apps/web/src/app/ map directly to URL paths, and every file is a React Server Component by default unless it starts with 'use client'.
Server Components execute strictly on the server, export metadata, and send finished HTML without shipping their own JavaScript. Only interactive parts that need clicks, form inputs, useState, or useEffect cross into a client component. Once server HTML paints, React runs hydration to attach browser listeners onto the existing DOM. Because hydration expects the first browser render to match server HTML identically, reading browser-only storage like localStorage during render raises React error 418 (a hydration mismatch); instead, initial markup stays deterministic and browser preferences sync inside useEffect.
In plain words
Public pages (/, /pricing, /trust, /methodology, /academy, /glossary) sit at the root of apps/web/src/app/, while tenant routes sit under the dynamic segment /w/[workspaceId]/... wrapped in one persistent app shell (WorkspaceShell): a 240-pixel desktop rail that turns into a compact header and bottom navigation bar on phones. Only NEXT_PUBLIC_ environment variables (NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_API_URL) enter browser bundles, carrying public addresses and never secrets.
Browser request: /w/mora-deri/overview
|
v
[Next.js Server] layout.tsx + page.tsx (Server Components, 0 KB client JS)
| exports metadata, awaits workspaceId from params
v
[Initial HTML] fast paint -> React hydrates only 'use client' islands
|
v
[Browser Client] WorkspaceShell + OverviewClient -> apiRequestJson()
|
+---> cookie hint (__Host-gd_signed_in=1) -> credentials: 'include' -> live_api
+---> explicit dev Bearer token string -> Authorization header -> live_api
+---> signed-out preview (null, no hint) -> local_sample_fallback -> "Sample data"2. Talking to the API honestly: cookie sessions, the three-way signal, and sample fallback
Screens never call raw fetch with ad-hoc headers. Every request flows through one API request helper (apiRequestJson) that rejects path traversal (.., encoded slashes, cross-origin URLs), serialises plain object bodies once, sends x-gd-request: 1 on non-GET mutations, scrubs secrets from error text, and tags each answer live_api or local_sample_fallback.
Real browser sessions use an HttpOnly cookie (__Host-gd_session) that JavaScript cannot read so XSS cannot steal it. To let browser code tell signed-in visitors apart from signed-out previews without exposing the secret cookie, the API sets a paired non-secret hint cookie (__Host-gd_signed_in=1). That drives the three-way session token signal:
Value of sessionToken | Meaning | Browser behaviour |
|---|---|---|
| Non-empty string | Explicit dev or test Bearer token | Sends Authorization: Bearer ... to live API |
null (hint cookie absent) | Signed-out offline preview | Stays offline and shows stamped sample fallback |
null (__Host-gd_signed_in=1 present) | Real cookie-authenticated browser | Sends credentials: 'include', no Bearer, calls live API |
undefined | Inspect active browser state | Reads browser cookie hint or dev token |
Two frequent mistakes break this helper: coercing sessionToken with ?? (which collapses explicit null into undefined) and double-serialising body before passing it in (which sends a quoted string instead of a JSON object). Equally strict is honesty: signed-out previews must display the sample data stamp (Örnek veri / Sample data), whereas a signed-in user's API error stays tagged live_api and shows a calm error banner—never silent sample numbers.
3. The closed UI kit and design tokens
Open styling codebases drift fast as pages invent custom greys, shadows, and button sizes. This repository locks visuals into one closed kit (packages/ui) governed by one design system.
Inside packages/ui/src/tokens.css, Tailwind CSS v4 @theme first wipes Tailwind's built-in scales (--color-*: initial, --radius-*: initial, --spacing-*: initial) and defines strictly our closed design tokens:
- Canvas, surface, ink and line: Four neutral families (
--canvasbackground,--surfaceto--surface-3sheets,--inkto--ink-3text, and--line1-pixel decorative hairlines) defined for both light and[data-theme="dark"]modes. - Control edge contrast: A stronger
--line-fieldtoken for inputs, selects, and outlined buttons so interactive borders always clear 3:1 contrast. - One accent colour: Signal Emerald-Pine (
--accentplus hover, subtle, text, and on-accent tokens), reserved for the one primary action per screen and active cues. - Three semantic tones and a 4 px grid:
ok,wait, andstopforeground/soft pairs, plus strict 4-pixel spacing steps (--spacing-11: 44pxfor touch targets).
No file outside tokens.css may hold a raw colour (literal hex or functional RGB/HSL). Every UI primitive in packages/ui/src/components/ exposes strictly closed cva variants, holds zero product copy or fetch imports, and receives every word through props.
Warning
4. The words rule, Turkish-first copy, and owner decisions
Under the words rule (AGENTS rule 17), user-facing text is authored first in design/WORDS.md under a dotted key and mirrored into apps/web/src/lib/words.ts (WORDS_TR and WORDS_EN). Five rules govern every string:
- Turkish first, English equal. Turkish runs 15 to 25 percent longer than English, so screens are sized for Turkish first while key parity (
tools/check-i18n.mjs) verifies an exact 1-to-1 match across both languages. - Whole sentences with named slots. Turkish places verbs last and keeps nouns singular after numbers (
2 onayvs2 approvals), so sentences live whole with named placeholders ({tutar},{tarih},{n}) instead of code concatenation. - Calm voice and zero banned words. Direct informal Turkish
senand plain English, exact numbers, two-sentence max errors explaining what failed and what to do next, zero exclamation marks, zero emoji, and zero hype or guaranteed-return claims. - Sentence case and the upper-case ban. Only the first word and proper nouns are capitalised. CSS all-caps transforms are banned everywhere because browser casing breaks Turkish dotted
İ/iand dotlessI/ı(bildirimturning intoBILDIRIM), and standard.toLowerCase()splitsİintoiplus combining dotU+0307. Search and tag controls therefore use Turkish-safe case folding (toLocaleLowerCase('tr-TR')). - Two explicit owner exceptions. Under
OD-20(3 December 2026), 1,455 legacy technical strings on older workspace pages stay as-is while Wave 46–48 owner flows (sign-in, connections, approval queue, delivery status) use plain everyday wording tested for zero leaked HTTP codes. UnderOD-23,/academyand/glossarylearning text is English-only fromdocs/lessons/anddocs/glossary/while site chrome stays bilingual.
5. Explicit screen states and progressive disclosure
Every screen designs explicitly for nine screen states so edge cases never turn into blank boxes or fake zeroes:
| State | Expected UI | Forbidden mistake |
|---|---|---|
loading | Static non-pulsing Skeleton blocks matching row height | Layout jump or blank white screen |
empty | Calm EmptyState with one next step | Table filled with fake zeroes |
error | Calm InlineAlert or RouteErrorState with retry and digest | Raw stack trace or silent sample fallback |
offline | Bağlantı yok banner or stamped offline preview | Presenting cached data as live |
partial | Explicit notice naming which connector lagged | Silently summing incomplete totals |
conflict | Clear 409 notice when another teammate acted first | Overwriting their decision silently |
permission | Calm Read-only mode (Okuma modu) notice | Unexplained disabled controls |
skipped_no_consent | Plain KVKK/IYS explanation for skipped send | Reporting legal skips as errors |
success | Concrete fact naming the exact record saved | Cheerleading filler or exclamation marks |
Numeric cells obey the same rule: null renders as — (unknown), never 0 (confirmed zero). Route state files (loading.tsx, not-found.tsx, error.tsx) catch unexpected crashes and display only an opaque correlation token (resolveErrorDigest).
To keep screens focused without removing deep diagnostics, workspace routes use progressive disclosure: primary figures sit first, followed by a concise Ayrıntılar (Details) index and collapsible disclosure sections built on native HTML <details> and <summary>. Native <details> toggles without JavaScript, works natively with screen readers, expands on #hash deep links, and opens completely on beforeprint.
6. Accessibility (WCAG 2.2 AA), motion discipline, and monochrome print
Every primitive and route targets WCAG 2.2 AA as an enforceable baseline:
- Contrast and symbols: At least
4.5:1for normal text,3:1for--line-fieldcontrol edges and focus rings, and never colour alone—StatusPillpairs tones with distinct shapes (●ok,◆wait,■stop),HeatmapGriduses○to●, andAllocationBarpairs five glyphs with pure-BigIntpercentages totalling exactly 100. - Semantic HTML, keyboard, and roving tabindex: Real
<button>,<a>,<nav>,<main>, and<details>elements replace clickable<div>boxes, images require explicitalt, headings never skip levels, and positivetabIndexis banned. Modals (Drawer,ConfirmDialog,CommandBar) trap Tab, focus Cancel first on destructive actions, close on Escape, and restore focus to their trigger. Composite widgets (TreeView,CalendarGrid,HeatmapGrid,AllocationBar) take one Tab stop via rovingtabindex(0on the active item,-1on siblings) and move with Arrow, Home, End, and Page keys.SliderandSplitPanenever depend on dragging alone. - Target size, 320-pixel reflow, and 200 percent zoom: Interactive controls enforce a minimum touch target of
44 x 44 px(min-h-11 min-w-11, stricter than WCAG's24 px), reflow down to320 pxwith0 pxhorizontal overflow, and expand without clipping at200%text zoom. - Motion and
prefers-reduced-motion: Daily actions (tabs, sorts, filters) snap in0 ms; overlays animate only GPU-compositedtransformandopacity(zerotransition: all); press feedback scales to97%over120 ms;Skeletonnever pulses;Toaststays until manually dismissed; and reduced-motion preferences collapse every transition to0 ms. - Monochrome print:
@media printinapps/web/src/app/globals.cssforces black ink on white paper even from dark mode, hides chrome and buttons, opens<Disclosure>panels viabeforeprint, and swapsAllocationBarfor archival monochrome tables.
7. Performance budgets, Higgsfield visuals, and proving screens in a browser
Core Web Vitals (LCP <= 2.5 s, INP <= 200 ms, CLS <= 0.1 at p75) and asset hygiene are protected statically and verified live:
- The web budget gate (
tools/check-web-budgets.mjs) blocks 16 heavy or vendor packages (moment,lodash,three,gsap,chart.js,recharts,framer-motion, proprietary LLM SDKs), verifies local/assets/**files with zero stock hosts, enforces verbatimsessionTokenforwarding and single JSON bodies, checks'use client'and zero Node built-ins in browser files, and bans mount-time fetches on watched public pages. - The media gate (
tools/check-media-assets.mjs) verifies all 17 Higgsfield WebPs and the Option B SVG for validRIFF....WEBPheaders, byte caps (<= 60 KiBavatars,< 250 KiBeditorial,<= 270 KiBhero,<= 2.5 MiBtotal), 100 percent SHA-256 parity withdesign/assets/anddesign/higgsfield/LOG.md, zero stock photos, and zero orphan files. - Three verification layers: Static gates run in under a second; Vitest suites (
renderToStaticMarkupand DOM checks) test ARIA roles,null -> —, and plain wording; and Playwright browser suites (a11y-tree-audit.mjsacross 40 routes,sign-in-journey-e2e.mjs,connect-journey-e2e.mjs,event-and-approval-journey-e2e.mjs, plusnext build+next startvisual audits at320,390, and1440 px) catch real hydration,useEffect, and overflow bugs static tests miss.
How this repository does it
Frontend code lives in two packages backed by six automated gates and real browser tests:
apps/web: Configured inweb package manifest(Next.js16.4.6, React19.3.1, Tailwind CSS4.3.5, TypeScript7.0.2, Vitest5.1.2) andNext.js config(output: 'standalone').Root layoutsets<html lang="tr" data-theme="light">andresolveMetadataBase;global stylesheetdefines@media print. Forty-four routes span public pages listed insitemap(includingcomponent catalogue) and 11 workspace route folders underworkspace layout,WorkspaceShell,workspace loading,workspace error,root error, andRouteErrorState. Client helpers live inapi-client.ts,workspace-context.tsx,words.ts,drill-downs.ts, andMotionPrimitives.tsx.packages/ui:UI package manifestdepends strictly onclass-variance-authority,clsx, andradix-ui.tokens.csslocks@theme, andindex.tsexports all 58 primitives—includingButton,StatusPill,DataTable,MoneyCell,Disclosure,TreeView, andAllocationBar—verified bya11y.test.tsx.
| Gate script | Enforces | Breaks if removed |
|---|---|---|
check-tokens.mjs | Zero raw colours, zero CSS all-caps, zero transition: all, pure packages/ui, zero working name in apps/web | Dark mode drifts, Turkish İ/ı breaks, kit leaks coupling |
check-surface-invariants.mjs | All 58 primitives cleanly exported and aligned | Hidden components drift from /design-system |
check-i18n.mjs | 1-to-1 WORDS_TR/WORDS_EN parity, zero ! or banned words | Missing keys or hype copy reach screens |
check-a11y-static.mjs | Semantic interactive tags, explicit alt, no positive tabIndex, visible focus, labelled dialogs | Keyboard and screen-reader bugs ship silently |
check-web-budgets.mjs | Bans 16 heavy packages, local /assets/**, verbatim sessionToken, single JSON body, zero public mount fetches | Bundles bloat, cookie sessions break, public routes trigger 401s |
check-media-assets.mjs | Valid WebPs, KiB caps, SHA-256 Higgsfield parity, zero stock URLs or orphans | Oversized or unverified visuals hurt LCP and provenance |
Live Playwright suites—a11y-tree-audit.mjs, sign-in-journey-e2e.mjs, connect-journey-e2e.mjs, and event-and-approval-journey-e2e.mjs—plus Wave 44 visual audit verify real rendered journeys.
Not built yet
What went wrong once
1. Eight-thousand-pixel workspace screens buried the main job (CS-20, Wave 45)
By Wave 44, overview stretched to 8,872 px because 76 diagnostic panels across 11 workspace routes loaded fully expanded. Adding native <details> Disclosure and drill-downs.ts collapsed all 76 panels behind a top Ayrıntılar index, cutting overview to 2,869 px while keeping #hash deep links, zero-JS toggling, and beforeprint expansion. Rule: one primary task first, secondary depth one click away.
2. Signed-in users saw sample data and a fake revoke receipt (CS-36 and CS-44, Waves 46–47)
Because __Host-gd_session is HttpOnly, browser code could not read it, passed sessionToken: null, treated real signed-in visitors as offline preview, showed stamped sample figures, and even returned a local synthetic revoke receipt on transport failure. Adding the non-secret __Host-gd_signed_in=1 hint cookie, hasLiveWorkspaceSession in api-client.ts, strict live_api error handling, and the ?? guard in check-web-budgets.mjs closed the gap. Rule: sample fallback serves signed-out previews only and never hides a real user's API error.
3. Legacy technical wording across 11 older screens (CS-21, Wave 45 and OD-20)
An audit found 1,455 technical labels across older workspace routes. Rather than risking a noisy bulk rewrite, the owners logged OD-20 in owner decisions (3 December 2026): keep legacy workspace strings as-is while enforcing plain everyday wording and zero raw HTTP codes on all newer Wave 46–48 sign-in, connection, and approval screens. Rule: record conscious scope boundaries openly in owner decisions.
4. Unknown approval IDs fell back to the first queue item (CS-52, Wave 48)
Opening /w/[workspaceId]/approvals/missing-id fell back to items[0] when the ID was absent from the fetched queue, risking approval of the wrong budget change. MobileApprovalClient.tsx now renders an explicit not-found state linking back to the queue. Rule: missing record IDs always show not-found, never another record.
Try it yourself
Every step below is read-only, runs inside the repository root in PowerShell or Git Bash, touches zero running dev servers, and makes zero external calls.
Step 1: Run the closed-kit token and surface gates
node tools/check-tokens.mjs
node tools/check-surface-invariants.mjsVerify PASS confirming zero raw colours outside tokens.css, zero CSS all-caps transforms, pure copy-free packages/ui, and all 58 primitives exported from packages/ui/src/index.ts.
Step 2: Run the accessibility, copy parity, web budget, and media gates
node tools/check-a11y-static.mjs
node tools/check-i18n.mjs
node tools/check-web-budgets.mjs
node tools/check-media-assets.mjsConfirm zero errors across interactive semantics, WORDS_TR/WORDS_EN parity, forbidden packages, verbatim sessionToken forwarding, zero public mount-time fetches, and 100 percent SHA-256 Higgsfield asset parity.
Step 3: Inspect the closed token sheet and monochrome print reset
git grep -n "initial;" packages/ui/src/tokens.css
git grep -n "@media print" apps/web/src/app/globals.cssSee how @theme clears Tailwind defaults, how [data-theme="dark"] swaps --canvas, --surface, --ink, --line, --line-field, and --accent, and how @media print forces monochrome paper output.
Step 4: Trace the three-way sessionToken signal
git grep -n "hasLiveWorkspaceSession\|SIGNED_IN_HINT_COOKIE_NAME\|local_sample_fallback" apps/web/src/lib/api-client.tsTrace how string, null with or without __Host-gd_signed_in=1, and undefined route between live_api and local_sample_fallback.
Check yourself
0 / 7Why can a React Server Component read server configuration while a 'use client' file must never import node:fs or secret environment variables?
A signed-in user carrying __Host-gd_session and __Host-gd_signed_in=1 opens overview while the API is unreachable. What must the screen show?
Why does tools/check-tokens.mjs ban CSS all-caps text transforms across apps/web and packages/ui?
Why must DataTable and MoneyCell render null spend as — instead of ₺0,00?
Why do TreeView, CalendarGrid, and AllocationBar use roving tabindex instead of tabIndex={0} on every item?
Why is Disclosure built on native HTML <details> and <summary> rather than a custom div toggle?
A Vitest test using renderToStaticMarkup passes on a component that reads localStorage during render, yet the live browser throws React error 418. Why?
Words to know
32Go deeper
- Repository rules and contracts:
AGENTS.md,design frame,visual rules,words dictionary,owner decisions, andindependent review. - Archived lessons replaced by this chapter:
archived lesson 07 on design systems, a11y, motion, and print,archived lesson 13 on Next.js App Router, RSC, and web budgets,archived lesson 21 on frontend security and webhooks,archived lesson 25 on the 50-primitive UI kit, andarchived lesson 31 on CalendarGrid and SEO guards. - Official framework docs: Next.js App Router, React Server Components, and Tailwind CSS v4 theme variables.
- Official standards: W3C WCAG 2.2, W3C WAI-ARIA APG, MDN details element, MDN prefers-reduced-motion, and web.dev Core Web Vitals.