|
| 1 | +# @repo/strapi-client Architecture Documentation |
| 2 | + |
| 3 | +## Package Overview |
| 4 | +**Purpose**: Modern Strapi CMS client with TanStack Query integration for Next.js applications |
| 5 | +**Version**: 0.0.0 (private workspace package) |
| 6 | +**Location**: `/packages/strapi-client/` |
| 7 | + |
| 8 | +## Core Dependencies |
| 9 | +- **@strapi/client**: ^1.5.0 - Official Strapi SDK for type-safe API calls |
| 10 | +- **@tanstack/react-query**: ^5.45.0 - Powerful data fetching and caching library |
| 11 | +- **react**: ^19.0.0 - React framework |
| 12 | + |
| 13 | +## Architecture Layers |
| 14 | + |
| 15 | +### 1. Client Configuration Layer (`client.ts`) |
| 16 | +- **strapiClient**: Core instance using official @strapi/client |
| 17 | +- **Configuration**: Environment-based (NEXT_PUBLIC_STRAPI_URL, STRAPI_API_TOKEN) |
| 18 | +- **Base URL**: Default `http://localhost:1337/api` with override capability |
| 19 | +- **Caching**: React cache functions (`cachedFind`, `cachedFindOne`) for server-side performance |
| 20 | + |
| 21 | +### 2. Type System Layer (`types.ts`) |
| 22 | +- **Response Types**: `StrapiResponse<T>` (collections), `StrapiSingleResponse<T>` (single items) |
| 23 | +- **Domain Entities**: Article, Author, Category, Footer, Media, SEO |
| 24 | +- **Query Parameters**: FilterParams, PaginationParams, PopulateParams, SortParams |
| 25 | +- **Bridge Pattern**: Transform functions converting Strapi responses to clean interfaces |
| 26 | + - `bridgeCollectionResponse<T>`: Generic collection transformer |
| 27 | + - `bridgeSingleResponse<T>`: Generic single item transformer |
| 28 | + - Entity-specific bridges (e.g., `bridgeArticleCollection`) |
| 29 | +- **Type Guards**: `isStrapiResponse`, `isStrapiSingleResponse` for runtime validation |
| 30 | +- **Utility**: `safeCastParams` for type-safe parameter handling |
| 31 | + |
| 32 | +### 3. Query Key Management (`queries/keys.ts`) |
| 33 | +- **Hierarchical Structure**: Follows TanStack Query best practices |
| 34 | +- **Root Key**: `['strapi']` for all queries |
| 35 | +- **Entity Keys**: |
| 36 | + - Articles: `['strapi', 'articles']` with ID/category/slug variations |
| 37 | + - Categories: `['strapi', 'categories']` with ID/slug variations |
| 38 | + - Footer: `['strapi', 'footer']` (single type) |
| 39 | + - Authors: `['strapi', 'authors']` with ID variations |
| 40 | +- **Benefits**: Precise cache invalidation, query grouping, namespace isolation |
| 41 | + |
| 42 | +### 4. Client-Side Hooks Layer (`hooks/`) |
| 43 | +- **Pattern**: Each entity has dedicated hooks file (articles.ts, categories.ts, footer.ts) |
| 44 | +- **Hook Types**: |
| 45 | + - Query hooks: `useArticles`, `useArticle`, `useArticleBySlug` |
| 46 | + - Mutation hooks: `useCreateArticle`, `useUpdateArticle`, `useDeleteArticle` |
| 47 | +- **Features**: |
| 48 | + - Automatic population of related data (author, category, media) |
| 49 | + - Configurable pagination and sorting |
| 50 | + - Intelligent cache management (5-30 minute staleTime) |
| 51 | + - TypeScript-first with full type safety |
| 52 | + |
| 53 | +### 5. SSR Utilities Layer (`ssr.ts`) |
| 54 | +- **Prefetch Functions**: Server-side data fetching for Next.js App Router |
| 55 | + - `prefetchArticles`: List with filters, pagination |
| 56 | + - `prefetchArticle`: Single by ID |
| 57 | + - `prefetchArticleBySlug`: Single by slug |
| 58 | + - `prefetchFeaturedArticles`: Filtered featured content |
| 59 | + - Similar patterns for categories and footer |
| 60 | +- **QueryClient Factory**: `createSSRQueryClient` with optimized defaults |
| 61 | + - StaleTime: 5 minutes (general), 30 minutes (single types) |
| 62 | + - GcTime: 10 minutes |
| 63 | + - Smart retry logic (skip 4xx errors, retry up to 3 times) |
| 64 | + - Server-optimized settings (no window focus refetch) |
| 65 | + |
| 66 | +### 6. Hook Factory Layer (`utils/hookFactory.ts`) |
| 67 | +- **Purpose**: DRY principle, reduce boilerplate, ensure consistency |
| 68 | +- **Factory Functions**: |
| 69 | + - `createFindHook<T>`: Generate collection query hooks |
| 70 | + - `createFindOneHook<T>`: Generate single item query hooks |
| 71 | + - `createCreateMutation<T>`: Generate create mutations |
| 72 | + - `createUpdateMutation<T>`: Generate update mutations |
| 73 | + - `createDeleteMutation<T>`: Generate delete mutations |
| 74 | + - `createSingleFindHook<T>`: For Strapi single types |
| 75 | + - `createSingleUpdateMutation<T>`: For single type updates |
| 76 | +- **Features**: |
| 77 | + - Automatic cache invalidation on mutations |
| 78 | + - Optimistic updates for better UX |
| 79 | + - Type-safe throughout with generics |
| 80 | + - Configurable defaults (staleTime, retry logic) |
| 81 | + |
| 82 | +## Key Architectural Patterns |
| 83 | + |
| 84 | +### 1. Bridge Pattern |
| 85 | +- **Problem**: Strapi's API format differs from ideal application data structure |
| 86 | +- **Solution**: Bridge functions transform responses at the boundary |
| 87 | +- **Benefits**: Clean internal interfaces, easier testing, API format independence |
| 88 | + |
| 89 | +### 2. Factory Pattern |
| 90 | +- **Problem**: Repetitive hook creation for each entity |
| 91 | +- **Solution**: Generic factories generate type-safe hooks programmatically |
| 92 | +- **Benefits**: 70% code reduction, consistency, easier maintenance |
| 93 | + |
| 94 | +### 3. Hierarchical Query Keys |
| 95 | +- **Problem**: Cache invalidation complexity |
| 96 | +- **Solution**: Nested key structure matching data relationships |
| 97 | +- **Benefits**: Precise invalidation, query grouping, debugging clarity |
| 98 | + |
| 99 | +### 4. Dual-Mode Data Fetching |
| 100 | +- **Client-Side**: React hooks with TanStack Query for interactive UIs |
| 101 | +- **Server-Side**: Prefetch functions for SSR/SSG with Next.js |
| 102 | +- **Benefits**: SEO optimization, faster initial loads, progressive enhancement |
| 103 | + |
| 104 | +## Performance Optimizations |
| 105 | + |
| 106 | +1. **Intelligent Caching**: |
| 107 | + - Variable staleTime (5-30 minutes based on data volatility) |
| 108 | + - Server-side React cache for deduplication |
| 109 | + - Query result caching with TanStack Query |
| 110 | + |
| 111 | +2. **Smart Population**: |
| 112 | + - Selective field fetching to reduce payload |
| 113 | + - Nested population for related entities |
| 114 | + - Different population strategies for list vs. detail views |
| 115 | + |
| 116 | +3. **Retry Strategy**: |
| 117 | + - Skip retries for client errors (4xx) |
| 118 | + - Exponential backoff for server errors |
| 119 | + - Maximum 3 retry attempts |
| 120 | + |
| 121 | +## Integration Points |
| 122 | + |
| 123 | +1. **Next.js App Router**: Full support for RSC and client components |
| 124 | +2. **TypeScript**: Complete type safety from API to UI |
| 125 | +3. **Environment Variables**: Configuration through env vars |
| 126 | +4. **Monorepo**: Workspace package with proper exports |
| 127 | + |
| 128 | +## Usage Examples |
| 129 | + |
| 130 | +### Client Component: |
| 131 | +```tsx |
| 132 | +import { useArticles } from '@repo/strapi-client'; |
| 133 | + |
| 134 | +function ArticleList() { |
| 135 | + const { data, isLoading } = useArticles({ |
| 136 | + pageSize: 10, |
| 137 | + filters: { featured: true } |
| 138 | + }); |
| 139 | + // ... |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +### Server Component: |
| 144 | +```tsx |
| 145 | +import { prefetchArticles, createSSRQueryClient } from '@repo/strapi-client'; |
| 146 | + |
| 147 | +async function Page() { |
| 148 | + const queryClient = createSSRQueryClient(); |
| 149 | + await prefetchArticles(queryClient, { pageSize: 10 }); |
| 150 | + // ... |
| 151 | +} |
| 152 | +``` |
| 153 | + |
| 154 | +## Future Considerations |
| 155 | + |
| 156 | +1. **WebSocket Support**: Real-time updates via Strapi's WebSocket API |
| 157 | +2. **Offline Support**: PWA capabilities with background sync |
| 158 | +3. **GraphQL Option**: Alternative to REST for complex queries |
| 159 | +4. **Rate Limiting**: Built-in rate limit handling for Strapi's free tier |
| 160 | +5. **Error Boundaries**: Specialized error handling for Strapi-specific errors |
| 161 | + |
| 162 | +## Best Practices |
| 163 | + |
| 164 | +1. Always use the provided hooks instead of direct API calls |
| 165 | +2. Leverage prefetch functions for SSR/SSG pages |
| 166 | +3. Use appropriate staleTime based on data update frequency |
| 167 | +4. Implement proper error handling with TanStack Query's error boundaries |
| 168 | +5. Utilize the factory pattern for new entity types |
| 169 | +6. Keep query keys hierarchical for effective cache management |
0 commit comments