Storefront Web & Mobile Application (apps/storefront)
This document is the authoritative engineering specification for apps/storefront (@debelu/storefront), the flagship client application serving university students, campus buyers, and student/merchant vendors across web, Android, and iOS platforms. Grounded directly in [App.tsx](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/src/App.tsx), [router.tsx](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/src/app/router.tsx), [nativeApp.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/src/native/nativeApp.ts), and the shared packages [@debelu/core](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/packages/core) and [@debelu/ui](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/packages/ui), this specification details the frontend architecture, state synchronization, security boundaries, native Capacitor bridges, and performance optimizations.
1. System Overview & Deployment Topology
The Debelu Storefront is built on React 19, Vite 6, and React Router DOM 7. It deploys as a static single-page application (SPA) distributed globally over Cloudflare Pages at app.debelu.com. In addition to web delivery, the application is packaged directly into native Android (.apk / .aab) and iOS (.ipa) application shells via Capacitor 8.
graph TD
subgraph ClientSurfaces [Client Form Factors]
Web[Web Browser: app.debelu.com]
Android[Android App: Google Play]
iOS[iOS App: Apple App Store]
end
subgraph StorefrontApp [apps/storefront Architecture]
Shell[App.tsx Bootstrap: TanStack Query + Helmet + Theme]
CapBridge[Capacitor Native Bridge: nativeApp.ts]
Router[Router Engine: router.tsx]
Buyer[Lazy: BuyerSection /buy/*]
Vendor[Lazy: VendorSection /sell/*]
AdminRedirect[Strict Origin Redirection -> admin.debelu.com]
State[Zustand & React Query Caches]
end
subgraph MonorepoDependencies [Shared Monorepo Libraries]
Core["@debelu/core<br/>Services, Schemas, Domain Types"]
UI["@debelu/ui<br/>Design System, Theme Tokens, Modals"]
end
subgraph BackendAPI [API Gateway]
API[debelu-backend: api.debelu.com]
Supabase[(Supabase Auth & Postgres)]
end
Web --> Shell
Android --> CapBridge --> Shell
iOS --> CapBridge --> Shell
Shell --> Router
Router --> Buyer
Router --> Vendor
Router --> AdminRedirect
Buyer --> State
Vendor --> State
State --> Core
Buyer --> UI
Vendor --> UI
Core --> API
Core --> Supabase1.1 Technical Stack & Core Invariants
- Runtime & Framework: React 19.x with functional components and React 19 Actions/Hooks.
- Build Tooling: Vite 6.x with
@vitejs/plugin-reactand Cloudflare Pages integration (@cloudflare/vite-plugin). - Routing: React Router DOM 7.x in data-router mode with code-split lazy routes.
- Asynchronous State: TanStack React Query v5 (
staleTime: 30_000,retry: 1,refetchOnWindowFocus: false). - Client State: Zustand v5 for cart persistence, campus selector, and modal orchestration.
- Form Architecture: React Hook Form v7 with
@hookform/resolvers/zodand strict Zod validation schemas. - Styling: Tailwind CSS v4 + PostCSS with unified design tokens sourced from
@debelu/ui/theme.css. - Mobile Wrapper: Capacitor 8.5 (
@capacitor/core,@capacitor/android,@capacitor/ios,@capacitor/push-notifications).
2. Security Architecture & Origin Segregation
Debelu adheres to strict Tier-1 security standards (Google/Meta pattern) regarding administrative surface isolation and cross-site privilege mitigation.
2.1 Complete Administrative Origin Isolation
sequenceDiagram
autonumber
participant Client as User Browser / Storefront
participant Router as router.tsx
participant AdminDomain as admin.debelu.com (Isolated Origin)
Client->>Router: Navigates to /admin/* or logs in as Staff
Note over Router: Intercepted by AdminExternalRedirect / RootRedirect
Router->>Router: Hard Origin Redirect (window.location.replace)
Router-->>AdminDomain: GET https://admin.debelu.com/admin/overview
Note over AdminDomain: Completely isolated bundle, CSP, and auth session- Zero Admin Code in Bundle: The storefront build artifacts (
dist/) strictly exclude all administrative controllers, KYC reviewer components, and payout reconciliation tools. - Hard Origin Redirection:typescript
// apps/storefront/src/app/router.tsx:31-47 const ADMIN_URL = (import.meta.env as unknown as Record<string, string>).VITE_ADMIN_URL || 'https://admin.debelu.com'; function AdminExternalRedirect() { useEffect(() => { const suffix = window.location.pathname + window.location.search + window.location.hash; const dest = suffix.startsWith('/admin') ? `${ADMIN_URL}${suffix}` : `${ADMIN_URL}/admin/overview`; window.location.replace(dest); }, []); return <SectionFallback />; } - Privilege Escalation Immunity: Any cross-site scripting (XSS) vulnerability affecting storefront buyer components cannot access administrative session tokens or sensitive governance RPCs.
2.2 Cross-Origin Session Handoff
Authentication originates primarily on the public marketing site (debelu.com/login). Upon successful OAuth or magic link verification, session credentials are securely transferred to the storefront via URL hash fragment, consumed, and cleared from the browser address bar immediately:
// apps/storefront/src/app/router.tsx:77-80
await consumeSessionHandoff();
const { data: { session } } = await supabase.auth.getSession();3. Application Lifecycle & Provider Hierarchy
The application root [App.tsx](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/src/App.tsx) wraps the component tree in an enterprise provider hierarchy ensuring maintenance gating, error boundary containment, and distributed telemetry.
graph TD
App[App.tsx] --> Maintenance{useMaintenanceMode()}
Maintenance -->|Maintenance Active| MScreen[MaintenanceScreen: Retry & Status Polling]
Maintenance -->|Operational| Boundary[AppErrorBoundary: Sentry Capture]
Boundary --> I18n[I18nProvider: Nigerian Campus Locales]
I18n --> Helmet[HelmetProvider: Dynamic SEO & OG Tags]
Helmet --> Query[QueryClientProvider: TanStack React Query v5]
Query --> Theme[ThemeProvider: Light / Dark Mode Tokens]
Theme --> Toast[ToastProvider: Sonner Notification System]
Toast --> Store[StoreProvider: Global Store Context]
Store --> RouterOutlet[RouterProvider: router.tsx]3.1 Maintenance Screen Interceptor
When platform governance flags an active maintenance window (GET /api/status), the entire application tree suspends rendering and renders MaintenanceScreen. The screen maintains a retry loop polling /api/status every 15 seconds, automatically reloading the browser once maintenance concludes.
3.2 Global Query & Mutation Error Observation
// apps/storefront/src/App.tsx:13-35
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 1,
refetchOnWindowFocus: false,
throwOnError: false,
},
mutations: {
onError: (error) => {
logger.error('[QueryClient] Mutation failed', error as Error);
},
},
},
});All failed network mutations and background query refetches are intercepted and transmitted to logger telemetry without interrupting client rendering.
4. Role-Based Routing & Section Partitioning
Debelu uses React Router DOM 7 code-split dynamic imports to partition the application by user persona:
apps/storefront/src/
├── app/
│ └── router.tsx # Master route table & role redirects
├── sections/
│ ├── buyer/
│ │ ├── BuyerSection.tsx # Buyer layout, bottom navigation, header
│ │ ├── routes/ # Buyer sub-routes (/buy/explore, /buy/orders)
│ │ └── views/ # Product details, checkout, cart views
│ └── vendor/
│ ├── VendorSection.tsx # Vendor portal, inventory manager, orders
│ ├── routes/ # Vendor sub-routes (/sell/catalog, /sell/wallet)
│ └── views/ # Product creator, payout setup, KYC view4.1 Route Directory Structure
| URL Route Prefix | Component Module | Persona / Access Scope | Key Features |
|---|---|---|---|
/ | RootRedirect | Public / Authenticated | Inspects active Supabase session and user role; auto-routes vendors to /sell and buyers to /buy. |
/buy/* | BuyerSection (Lazy) | Buyer / Student | Product search, campus filtering, Nduzi AI assistant floating trigger, checkout payment flow, order escrow tracking, 6-digit delivery PIN display. |
/sell/* | VendorSection (Lazy) | Certified Campus Vendor | Product listing creation, stock management, order fulfillment, delivery PIN verification, wallet balances, Paystack payout withdrawals. |
/login | LoginRedirect | Public | Redirects to marketing authentication portal with return URL parameter. |
/legal/* | StaticPages (Lazy) | Public | Terms of Service, Privacy Policy (NDPA), Safety Guidelines, Vendor Agreements. |
/admin/* | AdminExternalRedirect | Staff / Administrators | Hard redirection to isolated admin.debelu.com origin. |
5. State Management & Asynchronous Data Flow
Debelu separates client UI state (Zustand) from server-synchronized state (TanStack React Query).
flowchart LR
subgraph ServerSync [Server State: TanStack Query v5]
API[(debelu-backend REST)] -->|staleTime: 30s| QC[QueryCache]
QC --> useProducts[useProducts]
QC --> useOrders[useOrders]
QC --> useVendorWallet[useVendorWallet]
end
subgraph ClientState [Client UI State: Zustand v5]
useCartStore[useCartStore<br/>LocalCart Persistence]
useCampusStore[useCampusStore<br/>Active Campus Filter]
useUIStore[useUIStore<br/>Sheet & Modal Triggers]
end
subgraph ViewLayer [React Component Tree]
ProductCard[ProductCard Component]
CheckoutSheet[CheckoutSheet Component]
NduziChatModal[NduziChatModal Component]
end
useProducts --> ProductCard
useCartStore --> CheckoutSheet
useCampusStore --> ProductCard
useOrders --> CheckoutSheet5.1 Local Cart Invariant (cart-total.test.ts)
Shopping cart state is persisted locally in localStorage with offline support:
- Price recalculation strictly computes subtotals in kobo (
integerarithmetic) to avoid floating-point rounding errors. - Automatic campus boundary validation: Cart items from vendors operating on different university campuses display cross-campus delivery warnings or enforce multi-order splitting.
6. Native Mobile Integration (Capacitor 8)
Debelu executes within native Android and iOS mobile wrappers utilizing Capacitor bridges configured in [capacitor.config.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/capacitor.config.ts) and initialized via [nativeApp.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/apps/storefront/src/native/nativeApp.ts).
sequenceDiagram
autonumber
participant OS as Mobile OS (Android / iOS)
participant Cap as Capacitor Native Runtime
participant NativeApp as nativeApp.ts
participant Router as router.navigate
participant Push as nativePush Service
OS->>Cap: User taps Push Notification or Universal App Link
Cap->>NativeApp: appUrlOpen / pushNotificationActionPerformed
NativeApp->>NativeApp: Extract deep-link path (appPathFromUrl)
NativeApp->>Router: router.navigate('/buy/orders/ord_992104')
Note over NativeApp,Push: Member Session Change (Auth Switch)
NativeApp->>Push: nativePush.sync(userId)
Push->>Cap: Register Device Token
Push-->>OS: Token Synced with Backend
Note over NativeApp: User Logs Out (onBeforeSignOut)
NativeApp->>Push: nativePush.forgetThisDevice()
Note over Push: Prevents push notification leakage on shared devices6.1 Native Bridge Capabilities
- App Links & Universal Deep Linking:
- Matches inbound HTTPS deep links (
https://app.debelu.com/buy/product/:id) and custom URI schemes (debelu://*) and routes them directly inside the single-page application without reloading the webview.
- Matches inbound HTTPS deep links (
- Hardware Push Notification Synchronization:
- Automatically registers APNs (iOS) and FCM (Android) push tokens with the backend via
nativePush.sync(). - Shared Device Security: On member sign-out (
userService.onBeforeSignOut), the app triggersnativePush.forgetThisDevice()to unbind the device token in Supabase, preventing subsequent notifications from leaking to secondary users of the hardware.
- Automatically registers APNs (iOS) and FCM (Android) push tokens with the backend via
- Native Splash Screen & Status Bar:
- Manages automatic splash screen dismissal once the React hydration tree completes initial render.
7. Performance & Web Vitals Optimization
The storefront is engineered to achieve top-tier Google Core Web Vitals (CWV) metrics:
| Metric | Target (p75) | Architectural Optimization Implemented |
|---|---|---|
| Largest Contentful Paint (LCP) | $\le 2.2$ s | Critical CSS inlined in index.html; hero images preloaded via <link rel="preload">; Cloudflare R2 image resizing CDN. |
| Interaction to Next Paint (INP) | $\le 150$ ms | Code-split section boundaries; lightweight icons (hugeicons-react); passive touch listeners. |
| Cumulative Layout Shift (CLS) | $\le 0.05$ | Explicit aspect ratio bounding on product card media; skeleton loading states (GlobalLoading). |
8. Build, Testing & Deployment Pipelines
8.1 Build & Verification Commands
# Type check the storefront application
npm run type-check --workspace=@debelu/storefront
# Run Vitest unit tests (cart totals, wallet receipts, app links)
npm run test --workspace=@debelu/storefront
# Execute Playwright End-to-End and accessibility (a11y) tests
npm run test:e2e --workspace=@debelu/storefront
npm run a11y --workspace=@debelu/storefront
# Build optimized production bundle
npm run build --workspace=@debelu/storefront
# Deploy directly to Cloudflare Pages
npm run deploy --workspace=@debelu/storefront8.2 Capacitor Native Compilation
# Synchronize web assets into Android and iOS native wrappers
npm run cap:sync --workspace=@debelu/storefront
# Open Android Studio project for APK / App Bundle generation
npm run cap:open:android --workspace=@debelu/storefront
# Open Xcode project for iOS build and archiving
npm run cap:open:ios --workspace=@debelu/storefront9. Document Revision History
| Revision | Date | Lead Author | Scope of Changes | Status |
|---|---|---|---|---|
1.0.0 | 2026-10-05 | Principal Frontend Architect | Initial enterprise specification detailing React 19/Vite 6 SPA, strict origin admin segregation, TanStack Query v5, Capacitor native bridge, and Cloudflare Pages deployment. | Active Living Standard |