Skip to content

Commit 7f2c048

Browse files
committed
feat: strapi
1 parent b355f70 commit 7f2c048

23 files changed

Lines changed: 1579 additions & 2130 deletions

.claude/settings.local.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,12 @@
5151
"Bash(git remote get-url:*)",
5252
"Bash(pbpaste)",
5353
"Bash(pnpm --filter=@repo/strapi-client typecheck)",
54-
"Bash(git remote set-url:*)"
54+
"Bash(git remote set-url:*)",
55+
"Bash(pnpm --filter @repo/strapi-client typecheck)",
56+
"SlashCommand(/sc:reflect)",
57+
"mcp__serena__get_current_config",
58+
"mcp__serena__read_memory",
59+
"Bash(npx tsc:*)"
5560
],
5661
"deny": []
5762
},
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Auth Package Context (@repo/auth)
2+
3+
## Package Overview
4+
- **Name**: `@repo/auth`
5+
- **Purpose**: Authentication components and utilities for Next.js web app
6+
- **Technology**: NextAuth.js v5.0.0 (beta) with Next.js 15.3
7+
8+
## Architecture
9+
10+
### Core Dependencies
11+
- **next-auth**: 5.0.0-beta.29 (main auth provider)
12+
- **@t3-oss/env-nextjs**: Environment validation
13+
- **zod**: Schema validation
14+
- **next-themes**: Theme management integration
15+
- **server-only**: Server-side utilities
16+
17+
### File Structure
18+
```
19+
packages/auth/
20+
├── index.ts # Main exports (auth, authKit, handlers, signIn, signOut)
21+
├── server.ts # Server-side auth utilities (currentUser, types)
22+
├── client.tsx # Client components (UserButton, OrganizationSwitcher)
23+
├── provider.tsx # Auth provider wrapper
24+
├── middleware.ts # Auth middleware
25+
├── keys.ts # Auth configuration keys
26+
├── components/
27+
│ ├── sign-in.tsx # Sign-in component
28+
│ └── sign-up.tsx # Sign-up component
29+
└── package.json # Package configuration
30+
```
31+
32+
## Key Symbols
33+
34+
### index.ts Exports
35+
- `auth`: Main auth function with session handling
36+
- `authKit`: Core NextAuth configuration
37+
- `handlers`: Auth route handlers
38+
- `signIn`/`signOut`: Authentication actions
39+
40+
### server.ts Types & Functions
41+
- `currentUser`: Server-side user retrieval
42+
- Type definitions: `UserJSON`, `OrganizationJSON`, `OrganizationMembership`, etc.
43+
- Webhook types: `WebhookEvent`, `DeletedObjectJSON`
44+
45+
### client.tsx Components
46+
- `UserButton`: User profile/menu component
47+
- `OrganizationSwitcher`: Organization selection component
48+
- `useUser`: Client-side user hook
49+
50+
## Implementation Notes
51+
52+
### Auth Flow
53+
1. Uses NextAuth.js v5 beta with modern App Router support
54+
2. Integrates placeholder organization system ("default-org")
55+
3. Provides redirect functionality for unauthenticated users
56+
4. Server-side and client-side utilities for different contexts
57+
58+
### Integration Points
59+
- Middleware for route protection
60+
- Provider wrapper for React context
61+
- Pre-built sign-in/sign-up components
62+
- Organization-aware auth structure (future multi-tenant support)
63+
64+
### Development Status
65+
- Uses beta version of NextAuth.js (5.0.0-beta.29)
66+
- Placeholder organization system implemented
67+
- Ready for integration with web app authentication flows
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
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

CLAUDE.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ This is a hybrid monorepo combining next-forge (a Turborepo template) with Strap
1212

1313
### Development
1414
- `pnpm dev` - Start all applications in development mode
15-
- `pnpm dev:web` - Start only the Next.js web app (port 3000)
15+
- `pnpm dev:web` - Start only the Next.js web app (port 3001)
1616
- `pnpm dev:strapi` - Start only the Strapi CMS backend
1717
- `cd apps/strapi && pnpm develop` - Alternative way to start Strapi in development
1818

1919
### Building
2020
- `pnpm build` - Build all applications and packages
2121
- `pnpm build --filter=web` - Build only the web app
22-
- `pnpm build --filter=@repo/strapi` - Build only the Strapi app
22+
- `pnpm build --filter=strapi` - Build only the Strapi app
2323
- `pnpm analyze` - Analyze bundle sizes (web app)
2424

2525
### Code Quality
@@ -111,6 +111,6 @@ The project uses Turborepo with pnpm workspaces:
111111
- Strapi generates TypeScript types automatically in `apps/strapi/types/generated/`
112112
- Content API accessible at `http://localhost:1337/api/` in development
113113
- Upload files stored in `apps/strapi/public/uploads/` with multiple size variants
114-
- Web app runs on port 3001 in development (not 3000)
114+
- Web app runs on port 3001 in development (configured in package.json dev script)
115115
- Strapi client includes built-in rate limiting and caching for free tier optimization
116116
- Internationalization middleware handles locale routing automatically

0 commit comments

Comments
 (0)