Skip to content

Frontend Architecture

The frontend is built with Next.js 16.4.2, React 19.3.1 and Tailwind CSS 4, running on Node 26 in the Docker image.

Project Structure

frontend/
├── app/                        # Next.js App Router
│   ├── layout.tsx              # Root layout: SentryProvider + StagingBanner
│   ├── robots.ts, sitemap.ts   # SEO routes
│   ├── api/health/             # Route handler (container health check)
│   ├── (shop)/                 # Storefront route group (shop providers, Navigation, Footer, CookieConsent)
│   │   ├── page.tsx            # Homepage
│   │   ├── producten/          # Product listing + [slug] detail (server-rendered)
│   │   ├── collectie/[slug]/   # Ready-made collection article
│   │   ├── designer/           # Product designer (Fabric.js); ?voor=team opens the team mode
│   │   ├── designs/            # Saved designs (works anonymously)
│   │   ├── teamkleding/        # Team orders landing page (server-rendered)
│   │   ├── cart/, checkout/    # Cart, checkout, checkout/bedankt (thank-you)
│   │   ├── orders/[id]/        # Order confirmation / status (token for guests)
│   │   ├── offerte/[id]/       # Quote detail
│   │   ├── account/            # Account area (own layout): orders, quotes, designs, addresses, profile, wishlist
│   │   ├── login/, auth/       # Login, reset-password
│   │   └── contact/, faq/, over-ons/, privacy/, retouren/, voorwaarden/, cookies/
│   └── admin/                  # Staff admin (React, own provider stack, no PostHog)
│       ├── login/
│       └── (protected)/        # AdminHeader/AdminNav shell, staff + MFA check
├── components/
│   ├── header/, homepage/, Footer.tsx, Navigation.tsx, StagingBanner.tsx, CookieConsent.tsx
│   ├── WhatsAppVraagKnop.tsx, FAQAccordion.tsx, StaticPage.tsx, JsonLd.tsx
│   ├── products/, product-detail/, collection/, reviews/, seo/, newsletter/, teamkleding/
│   ├── ProductDesigner/        # Fabric.js canvas designer (components/, tabs, team/, hooks/, utils/)
│   ├── Designer/               # Product/colour/size selection wrapper around the designer
│   ├── designs/, quotes/, orders/, Cart/, checkout/, Account/, auth/
│   ├── personalization/, journey/
│   ├── admin/                  # Admin shell + feature folders (orders, products, pricing, cijfers, cms, …)
│   ├── providers/              # QueryProvider, SentryProvider, PostHogProvider, MotionProvider
│   └── ui/                     # Shared primitives (Skeleton, PasswordInput, motion/)
├── contexts/                   # AuthContext, CartContext, ThemeContext
├── hooks/
│   ├── api/                    # TanStack Query hooks per resource (+ queryKeys.ts)
│   ├── admin/                  # useAdminTable, useDebounce
│   └── useFocusTrap.ts, useUnsavedChanges.ts, useHydrated.ts
├── lib/
│   ├── api/client.ts           # Axios client (cookies + X-CSRFToken), per-resource API objects
│   ├── api/adminClient.ts      # Axios client for /api/admin/
│   ├── queryClient.ts          # TanStack Query defaults (staleTime 5 min, gcTime 30 min)
│   ├── loadSiteData.ts         # Server-side loaders (site settings, CMS pages), React cache()
│   ├── posthog.ts, privacyUrl.ts, sentry.ts, sentryClient.ts
│   ├── siteMetadata.ts, structuredData.ts, legacyRedirects.ts, whatsapp.ts, paymentMethods.ts
│   ├── teamOrder/              # Roster helpers: sizes URL param, pasted-list parser, round trip
│   └── design/, personalization/, queries/, admin/
├── instrumentation-client.ts   # PostHog + Sentry browser init
├── instrumentation.ts, sentry.server.config.ts, sentry.edge.config.ts
├── types/                      # index.ts (domain types), api.generated.ts (from OpenAPI)
├── e2e/                        # Playwright tests
└── public/                     # Static assets

fabric vs @types/fabric version mismatch

Runtime uses fabric@^7.4.0, but the type stubs are pinned to @types/fabric@^5.3.10. The v5 types don't fully describe the v7 API, so some Fabric.js call sites rely on local typing shims or any.

Rendering

  • Server components by default. app/(shop)/producten/[slug]/page.tsx is an async server component with generateMetadata: the product title, description and og: tags are in the first HTML, which also removed a hydration error (v1.50). The homepage and listing pages export static metadata via lib/siteMetadata.ts; JSON-LD comes from components/seo/ and lib/structuredData.ts.
  • Server-side data is fetched through the same API with lib/loadSiteData.ts (loadSiteSettings, loadPage), wrapped in React cache() so each request hits the API once. A failing API renders the page without that block instead of erroring.
  • Interactive pages (designer, cart, checkout, collection detail, admin) are 'use client' components that use the hooks in hooks/api/.
  • The product page offers "Voor jezelf | Voor een team" (OrderModeSwitch, SizeQuantityGrid, TeamPriceSummary) when team_order_enabled is on; the team path sends the customer to /designer?voor=team&sizes=S:2,M:6.
  • Legacy English paths and the old team paths (/team-order, /namen-nummers → /teamkleding) are 308 redirects in next.config.ts / lib/legacyRedirects.ts; PostHog requests are rewritten from /ingest/* to the EU ingest host.

Routes

Canonical customer routes are Dutch. /producten (+ /producten/[slug]) is the canonical product surface; older English paths exist only as permanent redirects.

Route Purpose Notes
/ Homepage Collection category from SiteSettings.homepage_collection_category
/producten, /producten/[slug] Product listing, product detail Detail is server-rendered; the listing filters on ?q= from the search field in the header (SearchBar, the shop's only search field)
/collectie/[slug] Ready-made design article Customer picks colour, size, quantity
/products, /products/[slug], /catalog — 308 → /producten…
/designer Product designer (Fabric.js) ?product= opens a product directly; ?voor=team&sizes=… opens the team mode (only if team_order_enabled)
/designs Saved designs Works anonymously (session)
/teamkleding Team orders landing page "Start je teambestelling" with the switch on, "Bekijk de kleding" off
/team-order, /namen-nummers — 308 → /teamkleding
/cart, /checkout, /checkout/bedankt Cart, checkout, thank-you page Checkout sends an idempotency key
/orders/[id] Order confirmation / status ?token= for guests
/offerte/[id] Quote detail Accept, convert, download
/orders — 308 → /account/orders
/account, /account/{orders,quotes,designs,addresses,profile,wishlist} Account area Own layout
/login, /auth/reset-password Authentication allauth headless
/contact, /faq, /over-ons, /privacy, /retouren, /voorwaarden, /cookies Static / CMS pages CMS pages via /api/pages/{slug}/
/admin/login, /admin/* Staff admin Staff only, MFA enforced

Admin areas under app/admin/(protected)/: dashboard, orders, productie (production board), products, categories, brands, colors, sizes, design-assets, designs, pricing (+ pricing/proefontwerp, the designer in preview mode), quotes, invoices, payments, boekhouding (Informer), customers, staff, pages, settings, cijfers (analytics incl. website tiles), health, backups, audit-logs, beveiliging (security/MFA).

Component Architecture

Component Organization

Components are organized by feature:

components/
├── [feature]/
│   ├── FeatureComponent.tsx
│   ├── FeatureComponent.stories.tsx  # Storybook (a handful of components so far)
│   └── index.ts                      # Barrel export

Jest unit tests live in the top-level frontend/__tests__/ folder (mirroring the components/ tree); Playwright E2E tests in frontend/e2e/.

Component Patterns

Presentational Components

interface ButtonProps {
  variant: 'primary' | 'secondary';
  children: React.ReactNode;
}

export function Button({ variant, children }: ButtonProps) {
  return <button className={styles[variant]}>{children}</button>;
}

Container Components

export function ProductList() {
  const { data: products } = useProducts({ category: categoryId });
  return <ProductGrid products={products} />;
}

Providers

Three provider stacks, composed in the layouts:

Layout Providers (outer → inner)
app/layout.tsx SentryProvider, StagingBanner
app/(shop)/layout.tsx QueryProvider → ThemeProvider → AuthProvider → PostHogProvider → MotionProvider → CartProvider; Navigation, Footer, CookieConsent, Toaster
app/admin/layout.tsx QueryProvider → ThemeProvider → AuthProvider; (protected)/layout.tsx adds the admin shell and redirects non-staff

PostHogProvider, MotionProvider, Navigation, Footer and CookieConsent are loaded with next/dynamic so they stay out of the initial bundle; the admin never loads PostHog.

State Management

Server State (TanStack Query)

All remote data goes through hooks in hooks/api/ (one file per resource, shared queryKeys.ts), built on the Axios clients in lib/api/:

const { data, isLoading, error } = useProducts({ category: categoryId });

lib/queryClient.ts sets staleTime to 5 minutes and gcTime to 30 minutes.

Client State (React Context)

  • AuthContext - session user, login/logout, auth hint in localStorage
  • CartContext - cart items, team order groups and operations (server cart via /api/cart/)
  • ThemeContext - light/dark/system preference

The old TeamOrderContext and NamesNumbersContext are gone (v1.53): a team order is server state (OrderGroup in the cart) and the roster lives in the Designer's component state while it is being typed.

const { items, addItem, removeItem, total } = useCart();

Local and browser state

Component state (useState), the Fabric.js canvas (with useCanvasHistory for undo/redo) and small localStorage conveniences (theme, cookie consent, auth hint). zustand is listed in package.json but is not imported anywhere; there is no global store library in use.

Observability

  • Sentry (@sentry/nextjs) wraps the app via SentryProvider in app/layout.tsx; the browser init lives in lib/sentryClient.ts and imports the SDK (including Session Replay) dynamically. Replays are only recorded when an error occurs. Server and edge runtimes use sentry.server.config.ts / sentry.edge.config.ts. The build (next.config.ts) uploads source maps to Sentry and, with POSTHOG_PERSONAL_API_KEY and POSTHOG_PROJECT_ID, also to PostHog Error tracking (lib/posthogSourcemaps.ts); the .map files are removed afterwards.
  • PostHog: instrumentation-client.ts initialises the SDK, lib/posthog.ts exposes identifyUser(), resetUser() and trackEvent() plus typed ecommerceEvents (incl. discount_code_applied / discount_code_rejected with a reason), tags every event with the environment, and PostHogProvider captures $pageview on route changes (shop routes only). Delivery depends on NEXT_PUBLIC_POSTHOG_KEY.
  • Privacy: lib/privacyUrl.ts replaces password-reset/verification keys and order ids with :key / :id before any event or breadcrumb leaves the browser (PostHog before_send, Sentry beforeSend).

Styling

Tailwind CSS 4 with design tokens in app/globals.css (:root, re-exposed through @theme inline):

:root {
  --primary: #15808d;        /* brand teal, darkened for WCAG AA */
  --primary-dark: #126b75;
  --accent: #dc2626;         /* CTA red */
}

@theme inline {
  --color-primary: var(--primary);
}

Visual Identity System

The "Freeze" brand visual language uses frost/ice effects:

Color Tokens: - --frost-50 … --frost-600 - frost blue scale - --ice-100 … --ice-400 - ice accents - --coral-400, --coral-500 - warm accent for CTAs

Utility Classes: - glass-frost - glassmorphism with backdrop-blur - frost-overlay - decorative ice pattern overlay - link-underline - animated underline on hover/focus

Animation Patterns (Motion 13):

// Entrance animations with stagger
<motion.div variants={containerVariants} initial="hidden" animate="visible">
  <motion.div variants={itemVariants}>...</motion.div>
</motion.div>

// Tactile feedback
<motion.button whileTap={{ scale: 0.95 }} transition={{ duration: 0.1 }}>

Product Designer

components/ProductDesigner/ is the Fabric.js 7 canvas editor (Designer.tsx, components/, hooks/, utils/):

  • Tabs (loaded on demand, TabLoading): TextTab, ShapesTab (clipart figures: single-colour figures can be recoloured, also with an Illustrator <style> block; gradients, patterns, filters and images count as multicolour; a figure with editable_text_index gets an editable text), ImageTab (uploads; .ai/.eps/.pdf are rasterised by the API), NamesTab, NamesNumbersTab (team mode only when team_order_enabled), OrderTab
  • ViewSwitcher for front/back/left/right, ToolNav, SidebarTabs, ContextPanel with TextPropertiesPanel (incl. a "Tekst" field), ClipartColorPanel, NameNumberStylePanel; FontDropdown (uploaded + Google fonts via useFontLoader), ColorDropdown
  • Print zones per view with boundaries and px→cm scale; live price preview via POST /api/designs/price-preview/. The design JSON carries canvasSize (and pricingVersion), so the API scales positions to the 600 × 800 reference frame (ZONE_REF_W/ZONE_REF_H in utils.ts) and phone and laptop price alike
  • useCanvasHistory (undo/redo), useKeyboardShortcuts, mobile drawers (MobileToolDrawer, MobileContextDrawer) and MobileBottomBar
  • DesignReviewPanel / components/designs/DesignApprovalControls.tsx: request review and show the review status; GuestWarningModal for anonymous saves (always offers "Doorgaan als gast")
  • OrderPanelDrawer / OrderTab add the design to the cart with colour, size and quantity; colour and size can still be changed there after designing (colorChange.ts: the design stays, and the customer is told when a size, side or element no longer fits; not in team mode); WhatsAppVraagKnop when whatsapp_buttons_enabled
  • Team mode (teamMode prop, from ?voor=team&sizes=): TeamOrderPanel and components/team/ (TeamAddBar with "+ Logo / + Tekst / + Naam / + Nummer", TeamSideTabs, TeamNamesSection, TeamRosterRows, TeamRosterDialog with a shirt preview per row, RosterPasteDialog for a list pasted from WhatsApp or Excel). One row per shirt is prefilled from sizes, duplicates and errors are flagged, useGroupPrice calls POST /api/cart/group-price/ and one button puts the team in the cart as an OrderGroup (POST /api/cart/groups/; "Aanpassen" updates the same group via PATCH). Roster helpers live in lib/teamOrder/
  • mode.ts: 'customer' (normal) or 'preview' (admin Proefontwerp page: same canvas and price engine, nothing is written)

components/Designer/ wraps it with product, colour and size selection for the /designer page (useDesigner reads product, voor and sizes from the URL).