# {Project Name} Frontend Architecture Document ## Table of Contents { Update this if sections and subsections are added or removed } - [Introduction](#introduction) - [Overall Frontend Philosophy & Patterns](#overall-frontend-philosophy--patterns) - [Detailed Frontend Directory Structure](#detailed-frontend-directory-structure) - [Component Breakdown & Implementation Details](#component-breakdown--implementation-details) - [Component Naming & Organization](#component-naming--organization) - [Template for Component Specification](#template-for-component-specification) - [State Management In-Depth](#state-management-in-depth) - [Store Structure / Slices](#store-structure--slices) - [Key Selectors](#key-selectors) - [Key Actions / Reducers / Thunks](#key-actions--reducers--thunks) - [API Interaction Layer](#api-interaction-layer) - [Client/Service Structure](#clientservice-structure) - [Error Handling & Retries (Frontend)](#error-handling--retries-frontend) - [Routing Strategy](#routing-strategy) - [Route Definitions](#route-definitions) - [Route Guards / Protection](#route-guards--protection) - [Build, Bundling, and Deployment](#build-bundling-and-deployment) - [Build Process & Scripts](#build-process--scripts) - [Key Bundling Optimizations](#key-bundling-optimizations) - [Deployment to CDN/Hosting](#deployment-to-cdnhosting) - [Frontend Testing Strategy](#frontend-testing-strategy) - [Component Testing](#component-testing) - [UI Integration/Flow Testing](#ui-integrationflow-testing) - [End-to-End UI Testing Tools & Scope](#end-to-end-ui-testing-tools--scope) - [Accessibility (AX) Implementation Details](#accessibility-ax-implementation-details) - [Performance Considerations](#performance-considerations) - [Internationalization (i18n) and Localization (l10n) Strategy](#internationalization-i18n-and-localization-l10n-strategy) - [Feature Flag Management](#feature-flag-management) - [Frontend Security Considerations](#frontend-security-considerations) - [Browser Support and Progressive Enhancement](#browser-support-and-progressive-enhancement) - [Change Log](#change-log) ## Introduction { This document details the technical architecture specifically for the frontend of {Project Name}. It complements the main {Project Name} Architecture Document and the UI/UX Specification. This document details the frontend architecture and **builds upon the foundational decisions** (e.g., overall tech stack, CI/CD, primary testing tools) defined in the main {Project Name} Architecture Document (`docs/architecture.md` or linked equivalent). **Frontend-specific elaborations or deviations from general patterns must be explicitly noted here.** The goal is to provide a clear blueprint for frontend development, ensuring consistency, maintainability, and alignment with the overall system design and user experience goals. } - **Link to Main Architecture Document (REQUIRED):** {e.g., `docs/architecture.md`} - **Link to UI/UX Specification (REQUIRED if exists):** {e.g., `docs/front-end-spec.md`} - **Link to Primary Design Files (Figma, Sketch, etc.) (REQUIRED if exists):** {From UI/UX Spec} - **Link to Deployed Storybook / Component Showcase (if applicable):** {URL} ## Overall Frontend Philosophy & Patterns { Describe the core architectural decisions and patterns chosen for the frontend. This should align with the "Definitive Tech Stack Selections" in the main architecture document and consider implications from the overall system architecture (e.g., monorepo vs. polyrepo, backend service structure). } - **Framework & Core Libraries:** {e.g., React 18.x with Next.js 13.x, Angular 16.x, Vue 3.x with Nuxt.js}. **These are derived from the 'Definitive Tech Stack Selections' in the main Architecture Document.** This section elaborates on *how* these choices are applied specifically to the frontend. - **Component Architecture:** {e.g., Atomic Design principles, Presentational vs. Container components, use of specific component libraries like Material UI, Tailwind CSS for styling approach. Specify chosen approach and any key libraries.} - **State Management Strategy:** {e.g., Redux Toolkit, Zustand, Vuex, NgRx. Briefly describe the overall approach – global store, feature stores, context API usage. **Referenced from main Architecture Document and detailed further in "State Management In-Depth" section.**} - **Data Flow:** {e.g., Unidirectional data flow (Flux/Redux pattern), React Query/SWR for server state. Describe how data is fetched, cached, passed to components, and updated.} - **Styling Approach:** **{Chosen Styling Solution, e.g., Tailwind CSS / CSS Modules / Styled Components}**. Configuration File(s): {e.g., `tailwind.config.js`, `postcss.config.js`}. Key conventions: {e.g., "Utility-first approach for Tailwind. Custom components defined in `src/styles/components.css`. Theme extensions in `tailwind.config.js` under `theme.extend`. For CSS Modules, files are co-located with components, e.g., `MyComponent.module.css`.} - **Key Design Patterns Used:** {e.g., Provider pattern, Hooks, Higher-Order Components, Service patterns for API calls, Container/Presentational. These patterns are to be consistently applied. Deviations require justification and documentation.} ## Detailed Frontend Directory Structure { Provide an ASCII diagram representing the frontend application\'s specific folder structure (e.g., within `src/` or `app/` or a dedicated `frontend/` root directory if part of a monorepo). This should elaborate on the frontend part of the main project structure outlined in the architecture document. Highlight conventions for organizing components, pages/views, services, state, styles, assets, etc. For each key directory, provide a one-sentence mandatory description of its purpose.} ### EXAMPLE - Not Prescriptive (for a React/Next.js app) ```plaintext src/ ├── app/ # Next.js App Router: Pages/Layouts/Routes. MUST contain route segments, layouts, and page components. │ ├── (features)/ # Feature-based routing groups. MUST group related routes for a specific feature. │ │ └── dashboard/ │ │ ├── layout.tsx # Layout specific to the dashboard feature routes. │ │ └── page.tsx # Entry page component for a dashboard route. │ ├── api/ # API Routes (if using Next.js backend features). MUST contain backend handlers for client-side calls. │ ├── globals.css # Global styles. MUST contain base styles, CSS variable definitions, Tailwind base/components/utilities. │ └── layout.tsx # Root layout for the entire application. ├── components/ # Shared/Reusable UI Components. │ ├── ui/ # Base UI elements (Button, Input, Card). MUST contain only generic, reusable, presentational UI elements, often mapped from a design system. MUST NOT contain business logic. │ │ ├── Button.tsx │ │ └── ... │ ├── layout/ # Layout components (Header, Footer, Sidebar). MUST contain components structuring page layouts, not specific page content. │ │ ├── Header.tsx │ │ └── ... │ └── (feature-specific)/ # Components specific to a feature but potentially reusable within it. This is an alternative to co-locating within features/ directory. │ └── user-profile/ │ └── ProfileCard.tsx ├── features/ # Feature-specific logic, hooks, non-global state, services, and components solely used by that feature. │ └── auth/ │ ├── components/ # Components used exclusively by the auth feature. MUST NOT be imported by other features. │ ├── hooks/ # Custom React Hooks specific to the 'auth' feature. Hooks reusable across features belong in `src/hooks/`. │ ├── services/ # Feature-specific API interactions or orchestrations for the 'auth' feature. │ └── store.ts # Feature-specific state slice (e.g., Redux slice) if not part of a global store or if local state is complex. ├── hooks/ # Global/sharable custom React Hooks. MUST be generic and usable by multiple features/components. │ └── useAuth.ts ├── lib/ / utils/ # Utility functions, helpers, constants. MUST contain pure functions and constants, no side effects or framework-specific code unless clearly named (e.g., `react-helpers.ts`). │ └── utils.ts ├── services/ # Global API service clients or SDK configurations. MUST define base API client instances and core data fetching/mutation services. │ └── apiClient.ts ├── store/ # Global state management setup (e.g., Redux store, Zustand store). │ ├── index.ts # Main store configuration and export. │ ├── rootReducer.ts # Root reducer if using Redux. │ └── (slices)/ # Directory for global state slices (if not co-located in features). ├── styles/ # Global styles, theme configurations (if not using `globals.css` or similar, or for specific styling systems like SCSS partials). └── types/ # Global TypeScript type definitions/interfaces. MUST contain types shared across multiple features/modules. └── index.ts ``` ### Notes on Frontend Structure: { Explain any specific conventions or rationale behind the structure. e.g., "Components are co-located with their feature if not globally reusable to improve modularity." AI Agent MUST adhere to this defined structure strictly. New files MUST be placed in the appropriate directory based on these descriptions. } ## Component Breakdown & Implementation Details { This section outlines the conventions and templates for defining UI components. Detailed specification for most feature-specific components will emerge as user stories are implemented. The AI agent MUST follow the "Template for Component Specification" below whenever a new component is identified for development. } ### Component Naming & Organization - **Component Naming Convention:** **{e.g., PascalCase for files and component names: `UserProfileCard.tsx`}**. All component files MUST follow this convention. - **Organization:** {e.g., "Globally reusable components in `src/components/ui/` or `src/components/layout/`. Feature-specific components co-located within their feature directory, e.g., `src/features/feature-name/components/`. Refer to Detailed Frontend Directory Structure.} ### Template for Component Specification { For each significant UI component identified from the UI/UX Specification and design files (Figma), the following details MUST be provided. Repeat this subsection for each component. The level of detail MUST be sufficient for an AI agent or developer to implement it with minimal ambiguity. } #### Component: `{ComponentName}` (e.g., `UserProfileCard`, `ProductDetailsView`) - **Purpose:** {Briefly describe what this component does and its role in the UI. MUST be clear and concise.} - **Source File(s):** {e.g., `src/components/user-profile/UserProfileCard.tsx`. MUST be the exact path.} - **Visual Reference:** {Link to specific Figma frame/component, or Storybook page. REQUIRED.} - **Props (Properties):** { List each prop the component accepts. For each prop, all columns in the table MUST be filled. } | Prop Name | Type | Required? | Default Value | Description | | :-------------- | :---------------------------------------- | :-------- | :------------ | :--------------------------------------------------------------------------------------------------------- | | `userId` | `string` | Yes | N/A | The ID of the user to display. MUST be a valid UUID. | | `avatarUrl` | `string \| null` | No | `null` | URL for the user\'s avatar image. MUST be a valid HTTPS URL if provided. | | `onEdit` | `() => void` | No | N/A | Callback function when an edit action is triggered. | | `variant` | `\'compact\' \| \'full\'` | No | `\'full\'` | Controls the display mode of the card. | | `{anotherProp}` | `{Specific primitive, imported type, or inline interface/type definition}` | {Yes/No} | {If any} | {MUST clearly state the prop\'s purpose and any constraints, e.g., \'Must be a positive integer.\'} | - **Internal State (if any):** { Describe any significant internal state the component manages. Only list state that is *not* derived from props or global state. If state is complex, consider if it should be managed by a custom hook or global state solution instead. } | State Variable | Type | Initial Value | Description | | :-------------- | :-------- | :------------ | :----------------------------------------------------------------------------- | | `isLoading` | `boolean` | `false` | Tracks if data for the component is loading. | | `{anotherState}`| `{type}` | `{value}` | {Description of state variable and its purpose.} | - **Key UI Elements / Structure:** { Provide a pseudo-HTML or JSX-like structure representing the component\'s DOM. Include key conditional rendering logic if applicable. **This structure dictates the primary output for the AI agent.** } ```html
User Avatar

{userName}

{userEmail}

{variant === 'full' && onEdit && }
``` - **Events Handled / Emitted:** - **Handles:** {e.g., `onClick` on the edit button (triggers `onEdit` prop).} - **Emits:** {If the component emits custom events/callbacks not covered by props, describe them with their exact signature. e.g., `onFollow: (payload: { userId: string; followed: boolean }) => void`} - **Actions Triggered (Side Effects):** - **State Management:** {e.g., "Dispatches `userSlice.actions.setUserName(newName)` from `src/store/slices/userSlice.ts`. Action payload MUST match the defined action creator." OR "Calls `updateUserProfileOptimistic(newData)` from a local `useReducer` hook."} - **API Calls:** {Specify which service/function from the "API Interaction Layer" is called. e.g., "Calls `userService.fetchUser(userId)` from `src/services/userService.ts` on mount. Request payload: `{ userId }`. Success response populates internal state `userData`. Error response dispatches `uiSlice.actions.showErrorToast({ message: 'Failed to load user details' })`.} - **Styling Notes:** - {MUST reference specific Design System component names (e.g., "Uses `