Skip to content

Frontend Application Architecture

The Arda Frontend Application is a web interface built to interact with the Arda System. It is designed to provide a responsive, secure, and intuitive user experience for managing items, orders, and kanban workflows.

The application is built using Next.js (App Router), TypeScript, and Tailwind CSS. It serves as the frontend interface for the Arda system, interacting with backend services via a robust API layer and providing a rich user experience through a component-based architecture.

ComponentTechnologyVersionPurpose
FrameworkNext.js15.3.2Core application framework (App Router)
LanguageTypeScript5.xStatic typing and developer tooling
UI LibraryReact19.xComponent-based UI rendering
StylingTailwind CSS4.xUtility-first CSS framework
ComponentsRadix UI-Headless, accessible UI primitives (via shadcn/ui)
StateReact Context-Global state (Auth, UI preferences)
AuthAWS Cognitov3 SDKIdentity and Access Management

The application uses the Next.js App Router (src/app), leveraging React Server Components (RSC) by default. This structure allows for:

  • Nested Layouts: layout.tsx files handle shared UI (sidebars, headers) across routes.
  • Route Groups: Directories like (auth) or functional groupings organize code without affecting URL paths.
  • Server-Side Rendering (SSR): Initial page loads are optimized for performance.

The application implements a BFF pattern using Next.js API Routes (src/app/api/...).

  • Proxy Role: The frontend client (browser) rarely calls the downstream Arda services directly. Instead, it calls its own local API.
  • Security Boundary: The local API routes attach sensitive credentials (like the ARDA_API_KEY) and enriched context headers (X-Tenant-Id, X-Author) before forwarding requests upstream.
  • Token Handling: JWT handling and validation are centralized here.

Authentication is a shared responsibility between the Client, the BFF, and AWS Cognito.

  1. Client-Side (AuthContext):
    • Manages the user session.
    • Stores accessToken and idToken in localStorage.
    • Handles Cognito flows: Sign In, Password Reset, Challenge Response.
  2. Transit:
    • Requests to /api/arda/... include the Authorization: Bearer <accessToken> header.
  3. BFF Layer (route.ts):
    • Validates the incoming JWT structure.
    • Extracts claims (User ID, Tenant ID) to form trusted headers.
    • Signs the upstream request with the system’s ARDA_API_KEY.

Authentication Context (src/contexts/AuthContext.tsx)

Section titled “Authentication Context (src/contexts/AuthContext.tsx)”

This context is the heart of client-side security. It provides:

  • user: The current authenticated user object.
  • refreshTokens(): Logic to proactively refresh expired AWS Cognito tokens.
  • checkAuth(): Validates local tokens on application mount.

A centralized, typed HTTP client wrapper.

  • Purpose: Abstracts fetch calls to the local BFF API.
  • getAuthHeaders(): Automatically injects valid tokens into requests. It checks token expiration and attempts a refresh if necessary before making the call.
  • handleApiResponse<T>(): Standardizes error parsing, handling standard HTTP errors and specific Arda API error formats (JSON/text).

API Route Handlers (src/app/api/.../route.ts)

Section titled “API Route Handlers (src/app/api/.../route.ts)”

These handlers serve as the secure gateway. A typical handler:

  1. Authenticates: Calls processJWTForArda(request) to verify the user.
  2. Transforms: Reads the request body or parameters.
  3. Forwards: Constructs a request to ${env.BASE_URL} with:
    • Authorization: Bearer ${env.ARDA_API_KEY}
    • X-Author: User’s ID from JWT.
    • X-Tenant-Id: Tenant ID from JWT.

The following sequence diagram illustrates the flow of creating an item, demonstrating the security context propagation.

PlantUML diagram

  • Component Composition: Features are built using atomic components from src/components/ui (buttons, inputs) combined into molecule-level domain components (e.g., CardStateDropdown).
  • Styling Strategy: Tailwind CSS is used exclusively.
    • Global styles in globals.css.
    • Component styles via utility classes (e.g., className="flex items-center p-4").
    • Dark mode support via next-themes and Tailwind’s dark: modifier.

The following tree highlights the architectural significance of key directories.

src/
├── app/ # Next.js App Router (Routes & API)
│ ├── api/ # BFF API Layer
│ │ ├── arda/ # Proxy routes for Arda Backend
│ │ └── auth/ # Auth related endpoints
│ ├── (routes)/ # Page routes (dashboard, items, etc.)
│ └── layout.tsx # Root layout (Providers, Global CSS)
├── components/
│ ├── ui/ # Reusable primitives (shadcn/ui)
│ │ └── button.tsx
│ ├── common/ # Shared domain components
│ │ └── app-header.tsx
│ └── [feature]/ # Feature-specific components
│ └── items/
├── contexts/ # Global State (Auth, UI)
├── lib/ # Core Utilities
│ ├── ardaClient.ts # Typed API Client
│ ├── jwt.ts # Token processing logic
│ └── utils.ts # General helpers
└── types/ # TypeScript Definitions
├── arda-api.ts # API Request/Response shapes
└── [domain].ts # Entity definitions (items, kanban)

Contains the application routes (Next.js App Router) and API endpoints. Each directory generally corresponds to a URL path.

The global layout.tsx defines the root HTML structure and global providers (Auth, Toast), and page.tsx renders the landing page or redirects to the main dashboard. globals.css defines global Tailwind styles and CSS variables.

This directory houses the backend-for-frontend API routes. These routes act as a proxy or orchestration layer between the frontend client and the backend services.

  • src/app/api/arda: The primary namespace for Arda-specific domain operations.
    • .../items: Endpoints for item management (CRUD, searching, uploading). Subdirectories handle specific item operations like upload-job, upload-status, and retrieving individual items by ID.
    • .../kanban: Endpoints for the Kanban system. Includes routes for card management (kanban-card) such as creating, updating, moving, and querying cards by status or item.
    • .../tenant: Endpoints for tenant-related operations, including context switching or agent-for functionalities.
    • .../user-account: Endpoints for user account management tasks.
  • src/app/api/auth: Handles authentication flows, engaging with AWS Cognito. Includes sub-routes for things like secret-hash.
  • src/app/api/debug: Utilities for debugging the application state or environment configuration.
  • src/app/api/email: Handles email sending functionality, such as order notifications.
RouteDescription
account-profileManages the user’s account profile view, displaying and editing user details
blogsBlog section using dynamic routing (e.g., [slug]) for individual posts
company-settingsInterface for managing company-level settings and tenant-wide preferences
dashboardMain landing view for authenticated users; aggregates key metrics
helpHelp center or support section with dynamic routes for articles
itemsMain interface for the Item Master; listing, searching, and viewing items
kanbanKanban board interface; drag-and-drop board for managing workflow items
order-queueOrder queue interface listing incoming or processing orders
receivingInterface for processing incoming inventory or shipments
reset-passwordPassword reset flow (sub-routes: email-sent, new, success)
scanInterface for QR code or barcode scanning for inventory lookup
settingsGeneral user settings covering preferences
signinSign-in page with login form and authentication context integration
signupSign-up page for new user registration (sub-route: success)

React components organized by scope and reusability.

DirectoryDescription
commonShared domain-specific components used across multiple features (e.g., AppHeader.tsx, DeleteConfirmationModal.tsx)
itemsComponents dedicated to the items feature: item lists, detail views, grid cells
scanComponents for the scan feature, including camera interface or scanner input
settingsComponents specific to the settings pages
sideBarApplication sidebar navigation components
signInComponents specific to the sign-in flow
tableData table rendering components
uiLow-level reusable UI primitives following the shadcn/ui pattern (button.tsx, input.tsx, dialog.tsx, etc.)

React Context Providers for global state management.

FileDescription
AuthContext.tsxManages user authentication state and session data
JWTContext.tsxHandles JWT storage and access
OrderQueueContext.tsxManages state for the order queue feature
SidebarVisibilityContext.tsxControls the visibility state of the sidebar

Use-case specific custom React hooks.

FileDescription
useAuthValidation.tsLogic for validating authentication state
useFormValidation.tsHelpers for form validation logic
use-mobile.tsHook to detect mobile viewports
useSidebarState.tsLogic for sidebar toggling

Core utility libraries and business logic helpers.

FileDescription
ardaClient.tsMain API client wrapper for interacting with Arda backend services
hubspot.ts / hubspot-knowledge.tsIntegration logic for HubSpot (CRM/Knowledge base)
jwt.tsUtilities for parsing and managing JSON Web Tokens
mappers/Data mapping functions transforming API responses to frontend models

Serverless function code for AWS Lambda triggers associated with Cognito.

  • auto-confirm-cognito-user: Logic to automatically confirm users in Cognito under certain conditions.
  • cognito-custom-forgot-password-message: Customizes the content of the password reset email sent by Cognito.

TypeScript type definitions covering the domain model.

FileDescription
arda-api.tsTypes defining the structure of API requests and responses
items.tsItem entity definitions
kanban.tsKanban card and board entity definitions
tenant.tsTenant entity definitions
user-account.tsUser account entity definitions
FilePurpose
package.json / package-lock.jsonProject dependencies and scripts
tsconfig.jsonTypeScript configuration
tailwind.config.js / postcss.config.jsTailwind CSS styling configuration
next.config.tsNext.js specific configuration
jest.config.js / jest.setup.tsTesting configuration using Jest
eslint.config.mjsLinting rules
CHANGELOG.mdVersion history
PERFORMANCE_OPTIMIZATION_REPORT.mdPerformance analysis documentation
JWT_LOGGING_GUIDE.mdGuidelines for handling JWT logging