| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 0 | 1 | 27 | 0% |
| Commands | 0 | 0 | 10 | 0% |
| Section tags | 1 | 0 | 10 | 9% |
What each file covers
Sections
0 shared · 1 only in A · 27 only in B- − Frontend Rules
- + CLAUDE.md
- + Standard Worflow
- + Workflow when working on a new task:
- + Development Commands
- + Core Development
- + Code Quality
- + Database Operations
- + Architecture Overview
- + Tech Stack
- + Key Architectural Patterns
- + Important Development Rules
- + Environment Variables
- + Import Conventions
- + File Naming
- + Code Quality Requirements
- + Coding Standards
- + Syntax & Structure
- + Functional Programming Rules
- + Type Safety & Error Handling
- + React Component Standards
- + Component Granularity & Organization
- + Advanced Component Architecture Patterns
- + Application Guidelines
- + Database Schema
- + Current Tables
- + Schema Location
- + Testing and Deployment
Commands
0 shared · 0 only in A · 10 only in B- + yarn dev
- + yarn build
- + yarn lint
- + yarn type-check
- + yarn clean
- + yarn lint:fix
- + yarn format:write
- + yarn db:push
- + yarn db:generate
- + yarn db:migrate
Section tags
1 shared · 0 only in A · 10 only in B- + setup
- + test
- + lint-format
- + code-style
- + architecture
- + types
- + security
- + database
- + ui
- + agent-behaviour
- do-not
Line diff
sportiz91/vibe-template · .cursor/rules/frontend.mdc
@@ −1 @@
1---
2description: Follow these rules when working on the frontend.
3globs:
4---
5### Frontend Rules
6
7Follow these rules when working on the frontend.
8
9It uses Next.js, Tailwind, Shadcn, and Framer Motion.
10
11#### General Rules
12
13- Use `lucide-react` for icons
14- useSidebar must be used within a SidebarProvider
15
16#### Components
17
18- Use divs instead of other html tags unless otherwise specified
19- Separate the main parts of a component's html with an extra blank line for visual spacing
20- Always tag a component with either `use server` or `use client` at the top, including layouts and pages
21
22##### Organization
23
24- All components be named using kebab case like `example-component.tsx` unless otherwise specified
25- Put components in `/_components` in the route if one-off components
26- Put components in `/components` from the root if shared components
27
28##### Data Fetching
29
30- Fetch data in server components and pass the data down as props to client components.
31- Use server actions from `/actions` to mutate data.
32
33##### Data Flow Architecture
34
35Follow this layered architecture pattern:
36- **React Components** → **Server Actions** → **Services** (when complex logic is needed)
37- Services handle domain-specific logic, external API integrations, and complex business rules
38- Keep Server Actions lightweight and focused on data validation and orchestration
39
40##### Server Components
41
42- Use `"use server"` at the top of the file.
43- Implement Suspense for asynchronous data fetching to show loading states while data is being fetched.
44- If no asynchronous logic is required for a given server component, you do not need to wrap the component in `<Suspense>`. You can simply return the final UI directly since there is no async boundary needed.
45- If asynchronous fetching is required, you can use a `<Suspense>` boundary and a fallback to indicate a loading state while data is loading.
46- Server components cannot be imported into client components. If you want to use a server component in a client component, you must pass the as props using the "children" prop
47- params in server pages should be awaited such as `const { courseId } = await params` where the type is `params: Promise<{ courseId: string }>`
48
49Example of a server layout:
50
51```tsx
52"use server"
53
54export default async function ExampleServerLayout({
55 children
56}: {
57 children: React.ReactNode
58}) {
59 return children
60}
61```
62
63Example of a server page (with async logic):
64
65```tsx
66"use server"
67
68import { Suspense } from "react"
69import { SomeAction } from "@/actions/some-actions"
70import SomeComponent from "./_components/some-component"
71import SomeSkeleton from "./_components/some-skeleton"
72
73export default async function ExampleServerPage() {
74 return (
75 <Suspense fallback={<SomeSkeleton className="some-class" />}>
76 <SomeComponentFetcher />
77 </Suspense>
78 )
79}
80
81async function SomeComponentFetcher() {
82 const { data } = await SomeAction()
83 return <SomeComponent className="some-class" initialData={data || []} />
84}
85```
86
87Example of a server page (no async logic required):
88
89```tsx
90"use server"
91
92import SomeClientComponent from "./_components/some-client-component"
93
94// In this case, no asynchronous work is being done, so no Suspense or fallback is required.
95export default async function ExampleServerPage() {
96 return <SomeClientComponent initialData={[]} />
97}
98```
99
100Example of a server component:
101
102```tsx
103"use server"
104
105interface ExampleServerComponentProps {
106 // Your props here
107}
108
109export async function ExampleServerComponent({
110 props
111}: ExampleServerComponentProps) {
112 // Your code here
113}
114```
115
116##### Client Components
117
118- Use `"use client"` at the top of the file
119- Client components can safely rely on props passed down from server components, or handle UI interactions without needing <Suspense> if there’s no async logic.
120- Never use server actions in client components. If you need to create a new server action, create it in `/actions`
121
122Example of a client page:
123
124```tsx
125"use client"
126
127export default function ExampleClientPage() {
128 // Your code here
129}
130```
131
132Example of a client component:
133
134```tsx
135"use client"
136
137interface ExampleClientComponentProps {
138 initialData: any[]
139}
140
141export default function ExampleClientComponent({
142 initialData
143}: ExampleClientComponentProps) {
144 // Client-side logic here
145 return <div>{initialData.length} items</div>
146}
147```
sportiz91/vibe-template · CLAUDE.md
@@ +1 @@
1# CLAUDE.md
2
3This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
5## Standard Worflow
6
7Use this workflow when working on a new task:
8
9### Workflow when working on a new task:
10
111. First, think through the problem, read the codebase for relevant files, and
12 write a plan to tasks/todo.md.
132. The plan should have a list of todo items that you can check off as you complete them.
143. Before you begin to work, check in with me and I verify the plan.
154. Then, begin working on the todo items, marking them as complete as you go.
165. Finally, add a review section to the todo.md file with a summary of the changes
17 you made and any other relevant information.
18
19Periodically make sure to commit when it makes sense to do so.
20
21## Development Commands
22
23**Important: This project uses yarn, not npm. Always use yarn commands.**
24
25**Node.js Version**: This project uses Node.js version 20.12.2 (see .nvmrc). Always ensure you're using the correct Node.js version before running any commands, especially linting and code quality tools.
26
27**To activate the correct Node.js version, run these commands first:**
28```bash
29export NVM_DIR="$HOME/.nvm"
30[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
31nvm use
32```
33
34**Note**: These commands load nvm and switch to the project's Node.js version. You need to run them in each new terminal session.
35
36### Core Development
37
38- `yarn dev` - Start development server
39- `yarn build` - Build for production
40- `yarn lint` - Run ESLint
41- `yarn type-check` - TypeScript type checking
42
43### Code Quality
44
45- `yarn clean` - Fix linting and format code (recommended after changes)
46- `yarn lint:fix` - Auto-fix linting issues
47- `yarn format:write` - Format code with Prettier
48
49### Database Operations
50
51- `yarn db:push` - Push schema changes to database
52- `yarn db:generate` - Generate new migrations
53- `yarn db:migrate` - Run pending migrations
54
55## Architecture Overview
56
57This is a full-stack Next.js application template with the following architecture:
58
59### Tech Stack
60
61- **Frontend**: Next.js 15 with App Router, React 19, TypeScript, Tailwind CSS, Shadcn/UI
62- **Backend**: PostgreSQL with Supabase, Drizzle ORM, Next.js Server Actions
63- **Auth**: Clerk authentication
64- **Payments**: Stripe integration
65- **Analytics**: PostHog
66- **AI**: OpenAI integration
67
68### Key Architectural Patterns
69
70#### Route Organization
71
72- **Route Groups**: `(auth)` for authentication pages, `(marketing)` for public pages
73- **Route-specific Components**: Use `_components` folder within routes for one-off components
74- **Layouts**: Separate layouts for different route groups
75
76#### Data Layer
77
78- **Server Actions**: Located in `/actions/` directory, organized by functionality
79- **Services**: Located in `/lib/services/` directory for complex business logic
80- **Database Schema**: Drizzle ORM schemas in `/db/schema/`
81- **Type Safety**: Use schema-generated types like InsertProfile and SelectProfile from your database schemas
82
83#### Data Flow Architecture
84
85Follow this layered architecture pattern:
86
87- **React Components** → **Server Actions** → **Services** (when complex logic is needed)
88- Services handle domain-specific logic, external API integrations, and complex business rules
89- Keep Server Actions lightweight and focused on data validation and orchestration
90
91#### Component Architecture
92
93- **UI Components**: Shadcn/UI components in `/components/ui/` (don't modify unless specified)
94- **Shared Components**: Reusable components in `/components/`
95- **Route-specific**: Components in `app/route/_components/`
96
97## Important Development Rules
98
99### Environment Variables
100
101- Always use centralized config: `serverConfig` and `publicEnv` from `@/lib/config`
102- Never use `process.env` directly in application code
103- Update `.env.example` when adding new environment variables
104
105### Import Conventions
106
107- Use `@/` for all imports from the app root
108- Import types from `@/types`
109- Import database types from `@/db/schema`
110- Import services from `@/lib/services`
111
112### File Naming
113
114- Use kebab-case for all files and folders
115- Type files: `example-types.ts` in `/types/` directory
116- Export all types in `types/index.ts`
117
118### Code Quality Requirements
119
120- **Always use the correct Node.js version (20.12.2)** before running any code quality commands
121- **Load nvm first**: Run the nvm commands above if you're in a new terminal session
122- Run `yarn clean` after making changes to ensure code quality
123- Use TypeScript interfaces over type aliases when possible
124- Follow the existing patterns in the codebase
125
126## Coding Standards
127
128All code must adhere to these strict formatting and quality guidelines:
129
130### Syntax & Structure
131
132- File names must be dash-case (word-cloud.service.ts) unless an existing pattern differs
133- Group imports: node/standard → npm packages → internal paths. No unused imports
134- Use arrow functions everywhere except inside class bodies, where concise method syntax is allowed
135- Prefer early returns; nested if/else blocks deeper than two levels are disallowed
136- Early returns must use block format with braces (e.g., `if (!value) { return }`) for readability
137- Extract function call results as scope variables before using in conditions (e.g., `const trimmedText = text.trim(); if (!trimmedText) {...}` instead of `if (!text.trim()) {...}`)
138- Use async/await—never chain .then()
139- No .forEach for side effects; use for (const x of arr) instead
140- Array combinators (map, reduce, filter) are allowed only when you return their result
141- Identifiers must be English
142- No commented code allowed
143
144### Functional Programming Rules
145
146Each function must:
147
148- Be ≤ 50 lines (preferably; extract helpers if longer)
149- Take ≤ 4 parameters (optional ones last)
150- Have a single responsibility
151- Be pure unless it is an intentional I/O wrapper (e.g. DB write); such wrappers must be ≤ 15 lines
152- Name functions with camelCase imperative verbs (calculateTotals, getUserById)
153
154### Type Safety & Error Handling
155
156- Explicitly type all function parameters, return types, and exported constants
157- Type all local variables inside a function
158- **Special attention for async operations**: Variables from awaited functions (e.g., `const { userId } = await auth()`) must be explicitly typed, especially in Next.js components where auth results should use proper domain types
159- No any; if an external library forces it, wrap and narrow
160- Error handling in catch blocks:
161 - If the error variable is not used, use `catch {}` (no parameter)
162 - If the error is used, type it as `unknown` and handle it safely within the catch block
163
164### React Component Standards
165
166- Always define props with interfaces, never inline types
167- Place interfaces directly above component definitions
168- Use const arrow functions for component definitions
169- Use implicit return syntax when components only return JSX (no logic before return)
170- Export components using export default pattern (required for Next.js pages/layouts)
171- Handler functions inside components must be ≤ 20 lines and have a single, clear responsibility. Extract helper functions for complex logic.
172
173 **Wrong (~50 lines in one handler):**
174
175 ```tsx
176 const handleFormSubmit = async (): Promise<void> => {
177 const trimmedName: string = formData.name.trim()
178 const trimmedEmail: string = formData.email.trim()
179 const trimmedMessage: string = formData.message.trim()
180
181 if (!trimmedName) {
182 setErrors({ ...errors, name: "Name is required" })
183 toast({
184 title: "Error",
185 description: "Name is required",
186 variant: "destructive"
187 })
188 return
189 }
190
191 if (!trimmedEmail || !trimmedEmail.includes("@")) {
192 setErrors({ ...errors, email: "Valid email is required" })
193 toast({
194 title: "Error",
195 description: "Valid email is required",
196 variant: "destructive"
197 })
198 return
199 }
200
201 if (!trimmedMessage || trimmedMessage.length < 10) {
202 setErrors({
203 ...errors,
204 message: "Message must be at least 10 characters"
205 })
206 toast({
207 title: "Error",
208 description: "Message too short",
209 variant: "destructive"
210 })
211 return
212 }
213
214 setIsSubmitting(true)
215 setErrors({})
216
217 try {
218 const payload: FormPayload = {
219 name: trimmedName,
220 email: trimmedEmail,
221 message: trimmedMessage,
222 timestamp: new Date().toISOString()
223 }
224
225 const response: Response = await fetch("/api/contact", {
226 method: "POST",
227 headers: { "Content-Type": "application/json" },
228 body: JSON.stringify(payload)
229 })
230
231 if (!response.ok) {
232 throw new Error("Failed to submit")
233 }
234
235 const result: SubmissionResult = await response.json()
236
237 setFormData({ name: "", email: "", message: "" })
238 setSubmissionCount((prev) => prev + 1)
239
240 toast({ title: "Success", description: "Message sent successfully!" })
241
242 if (onSuccess) {
243 onSuccess(result)
244 }
245 } catch (error: unknown) {
246 const errorMessage: string =
247 error instanceof Error ? error.message : "Unknown error"
248 console.error("Submission error:", errorMessage)
249 setErrors({ submit: "Failed to send message" })
250 toast({
251 title: "Error",
252 description: "Failed to send message",
253 variant: "destructive"
254 })
255 } finally {
256 setIsSubmitting(false)
257 }
258 }
259 ```
260
261 **Good (broken into focused helpers ≤ 20 lines each):**
262
263 ```tsx
264 const validateForm = (): boolean => {
265 const trimmedName: string = formData.name.trim()
266 const trimmedEmail: string = formData.email.trim()
267 const trimmedMessage: string = formData.message.trim()
268
269 if (!trimmedName) {
270 setErrors({ ...errors, name: "Name is required" })
271 toast({
272 title: "Error",
273 description: "Name is required",
274 variant: "destructive"
275 })
276 return false
277 }
278
279 if (!trimmedEmail || !trimmedEmail.includes("@")) {
280 setErrors({ ...errors, email: "Valid email is required" })
281 toast({
282 title: "Error",
283 description: "Valid email is required",
284 variant: "destructive"
285 })
286 return false
287 }
288
289 if (!trimmedMessage || trimmedMessage.length < 10) {
290 setErrors({
291 ...errors,
292 message: "Message must be at least 10 characters"
293 })
294 toast({
295 title: "Error",
296 description: "Message too short",
297 variant: "destructive"
298 })
299 return false
300 }
301
302 return true
303 }
304
305 const submitForm = async (): Promise<SubmissionResult> => {
306 const payload: FormPayload = {
307 name: formData.name.trim(),
308 email: formData.email.trim(),
309 message: formData.message.trim(),
310 timestamp: new Date().toISOString()
311 }
312
313 const response: Response = await fetch("/api/contact", {
314 method: "POST",
315 headers: { "Content-Type": "application/json" },
316 body: JSON.stringify(payload)
317 })
318
319 if (!response.ok) {
320 throw new Error("Failed to submit")
321 }
322
323 return response.json()
324 }
325
326 const handleSuccess = (result: SubmissionResult): void => {
327 setFormData({ name: "", email: "", message: "" })
328 setSubmissionCount((prev: number) => prev + 1)
329 toast({ title: "Success", description: "Message sent successfully!" })
330
331 if (onSuccess) {
332 onSuccess(result)
333 }
334 }
335
336 const handleError = (error: unknown): void => {
337 const errorMessage: string =
338 error instanceof Error ? error.message : "Unknown error"
339 console.error("Submission error:", errorMessage)
340 setErrors({ submit: "Failed to send message" })
341 toast({
342 title: "Error",
343 description: "Failed to send message",
344 variant: "destructive"
345 })
346 }
347
348 const handleFormSubmit = async (): Promise<void> => {
349 const isValid: boolean = validateForm()
350
351 if (!isValid) {
352 return
353 }
354
355 setIsSubmitting(true)
356 setErrors({})
357
358 try {
359 const result: SubmissionResult = await submitForm()
360 handleSuccess(result)
361 } catch (error: unknown) {
362 handleError(error)
363 } finally {
364 setIsSubmitting(false)
365 }
366 }
367 ```
368
369- Example with implicit return:
370
371 ```tsx
372 interface MyComponentProps {
373 title: string
374 children: React.ReactNode
375 }
376
377 const MyComponent = ({ title, children }: MyComponentProps) => (
378 <div>
379 {title}
380 {children}
381 </div>
382 )
383
384 export default MyComponent
385 ```
386
387- Example with explicit return (when logic is present):
388
389 ```tsx
390 interface MyComponentProps {
391 title: string
392 children: React.ReactNode
393 }
394
395 const MyComponent = ({ title, children }: MyComponentProps) => {
396 const processedTitle = title.toUpperCase()
397
398 return (
399 <div>
400 {processedTitle}
401 {children}
402 </div>
403 )
404 }
405
406 export default MyComponent
407 ```
408
409- Normal components that are not Next.js pages/layouts should be exported
410 using export const pattern
411- Example with implicit return:
412
413 ```tsx
414 interface NotAPageOrLayoutComponentProps {
415 title: string
416 children: React.ReactNode
417 }
418
419 export const NotAPageOrLayoutComponent = ({
420 title,
421 children
422 }: NotAPageOrLayoutComponentProps) => (
423 <div>
424 {title}
425 {children}
426 </div>
427 )
428 ```
429
430### Component Granularity & Organization
431
432- Break down large components into smaller, focused components for better maintainability
433- When a component contains multiple logical sections (e.g., Card with CardHeader + CardContent), extract each section into separate components
434- Create dedicated folders for related component groups:
435 - Use kebab-case folder names matching the main component concept
436 - Place related sub-components within the same folder using kebab-case file names
437 - Example structure: `component-name/component-name-header.tsx`, `component-name/component-name-content.tsx`
438- Each sub-component should have a single, clear responsibility
439- Maintain the parent component as a composition wrapper that orchestrates child components
440- Follow this pattern when refactoring existing components or creating new feature components
441
442### Advanced Component Architecture Patterns
443
444#### Pure Functions and Constants Organization
445
446- **Pure functions** (no side effects, deterministic output) must be extracted outside components:
447 - Place above the component definition
448 - Examples: `getGreeting()`, `getMembershipBadgeColor()`, `formatDate()`
449- **Constants and static data** must be moved outside components:
450 - Place after imports and interfaces, before pure functions
451 - Use SCREAMING_SNAKE_CASE for naming (e.g., `TEMPLATE_FEATURES`, `TECH_STACK`) constants
452 - **Always explicitly type constants** with appropriate type annotations
453 - Examples: `const API_URL: string = "..."`, `const MAX_RETRIES: number = 3`
454 - Use `as const` for immutable values when type inference is sufficient
455 - Group related constants together
456
457#### Custom Hooks Organization
458
459- **Custom hooks** must be extracted to separate files in the `/hooks/` directory:
460 - Use kebab-case file naming: `use-scroll-detection.ts`, `use-local-storage.ts`
461 - Start hook names with `use` prefix following React conventions
462 - Place hooks in `/hooks/` folder at project root level
463 - Export hooks using named exports: `export const useScrollDetection = () => {}`
464 - **Always explicitly type hook return values** and parameters
465 - Examples: `useScrollDetection(): boolean`, `useLocalStorage<T>(key: string): [T, (value: T) => void]`
466 - Group related hooks in the same file only if they're tightly coupled
467
468#### Whitespace and Formatting Rules
469
470- **Component variable organization**: Maintain consistent whitespace between different types of declarations:
471 - Add a blank line between React state declarations and custom hook calls
472 - Add a blank line between custom hook calls and other variable declarations
473 - Example:
474
475 ```tsx
476 const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false)
477 const [isVisible, setIsVisible] = useState<boolean>(true)
478
479 const isScrolled: boolean = useScrollDetection()
480 const userData: UserData = useUserData()
481
482 const processedData: ProcessedData = processUserData(userData)
483 ```
484
485#### Nested Component Structure for Complex Components
486
487When a component has multiple distinct sections, create nested folder structure:
488
489```
490dashboard-welcome/
491├── dashboard-welcome.tsx // Main orchestrator component
492├── greeting.tsx // Self-contained greeting section
493├── whats-included/ // Folder for multi-part section
494│ ├── whats-included.tsx // Section orchestrator
495│ ├── whats-included-title.tsx // Title sub-component
496│ └── whats-included-features.tsx // Features list sub-component
497├── core-technologies/ // Folder for multi-part section
498│ ├── core-technologies.tsx // Section orchestrator
499│ ├── core-technologies-title.tsx // Title sub-component
500│ └── core-technologies-list.tsx // Tech list sub-component
501└── get-started/ // Folder for multi-part section
502 ├── get-started.tsx // Section orchestrator
503 ├── get-started-title.tsx // Title sub-component
504 ├── get-started-features.tsx // Features grid sub-component
505 └── get-started-feature-2.tsx // Individual feature card
506```
507
508#### Component Organization Rules
509
5101. **Main orchestrator**: Composition only, minimal logic, imports and renders sub-components
5112. **Section orchestrators**: Handle section-specific logic, render related sub-components
5123. **Leaf components**: Single responsibility, pure presentation, accept props only
5134. **Shared constants**: Extract to file level, use proper naming conventions
5145. **Pure functions**: Extract above component definitions, properly typed
5156. **File structure**: Mirror logical component hierarchy in folder structure
516
517### Application Guidelines
518
5191. Apply these standards to all new code and when refactoring existing code
5202. When making any code changes, ensure they conform to these guidelines
5213. If existing code doesn't follow these standards, update it to comply when modifying those files
5224. Use these standards as a checklist when reviewing code changes
5235. Prefer extracting helper functions over writing long, complex functions
5246. Always prioritize code readability and maintainability
525
526## Database Schema
527
528### Current Tables
529
530- **Profiles**: User profiles with Stripe integration and membership tiers
531
532### Schema Location
533
534- Schemas: `/db/schema/`
535- Migrations: `/db/migrations/`
536- Database connection: `/db/db.ts`
537
538## Testing and Deployment
539
540- The project uses Vercel for deployment
541- No specific test framework is configured - check with user if testing is needed
542- Always run `yarn build` and `yarn type-check` before considering work complete
543
@@ −1 +1 @@
1−---
2−description: Follow these rules when working on the frontend.
3−globs:
4−---
5−### Frontend Rules
1+# CLAUDE.md
62
7−Follow these rules when working on the frontend.
3+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
84
9−It uses Next.js, Tailwind, Shadcn, and Framer Motion.
5+## Standard Worflow
106
11−#### General Rules
7+Use this workflow when working on a new task:
128
13−- Use `lucide-react` for icons
14−- useSidebar must be used within a SidebarProvider
9+### Workflow when working on a new task:
1510
16−#### Components
11+1. First, think through the problem, read the codebase for relevant files, and
12+ write a plan to tasks/todo.md.
13+2. The plan should have a list of todo items that you can check off as you complete them.
14+3. Before you begin to work, check in with me and I verify the plan.
15+4. Then, begin working on the todo items, marking them as complete as you go.
16+5. Finally, add a review section to the todo.md file with a summary of the changes
17+ you made and any other relevant information.
1718
18−- Use divs instead of other html tags unless otherwise specified
19−- Separate the main parts of a component's html with an extra blank line for visual spacing
20−- Always tag a component with either `use server` or `use client` at the top, including layouts and pages
19+Periodically make sure to commit when it makes sense to do so.
2120
22−##### Organization
21+## Development Commands
2322
24−- All components be named using kebab case like `example-component.tsx` unless otherwise specified
25−- Put components in `/_components` in the route if one-off components
26−- Put components in `/components` from the root if shared components
23+**Important: This project uses yarn, not npm. Always use yarn commands.**
2724
28−##### Data Fetching
25+**Node.js Version**: This project uses Node.js version 20.12.2 (see .nvmrc). Always ensure you're using the correct Node.js version before running any commands, especially linting and code quality tools.
2926
30−- Fetch data in server components and pass the data down as props to client components.
31−- Use server actions from `/actions` to mutate data.
27+**To activate the correct Node.js version, run these commands first:**
28+```bash
29+export NVM_DIR="$HOME/.nvm"
30+[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
31+nvm use
32+```
3233
33−##### Data Flow Architecture
34+**Note**: These commands load nvm and switch to the project's Node.js version. You need to run them in each new terminal session.
3435
36+### Core Development
37+
38+- `yarn dev` - Start development server
39+- `yarn build` - Build for production
40+- `yarn lint` - Run ESLint
41+- `yarn type-check` - TypeScript type checking
42+
43+### Code Quality
44+
45+- `yarn clean` - Fix linting and format code (recommended after changes)
46+- `yarn lint:fix` - Auto-fix linting issues
47+- `yarn format:write` - Format code with Prettier
48+
49+### Database Operations
50+
51+- `yarn db:push` - Push schema changes to database
52+- `yarn db:generate` - Generate new migrations
53+- `yarn db:migrate` - Run pending migrations
54+
55+## Architecture Overview
56+
57+This is a full-stack Next.js application template with the following architecture:
58+
59+### Tech Stack
60+
61+- **Frontend**: Next.js 15 with App Router, React 19, TypeScript, Tailwind CSS, Shadcn/UI
62+- **Backend**: PostgreSQL with Supabase, Drizzle ORM, Next.js Server Actions
63+- **Auth**: Clerk authentication
64+- **Payments**: Stripe integration
65+- **Analytics**: PostHog
66+- **AI**: OpenAI integration
67+
68+### Key Architectural Patterns
69+
70+#### Route Organization
71+
72+- **Route Groups**: `(auth)` for authentication pages, `(marketing)` for public pages
73+- **Route-specific Components**: Use `_components` folder within routes for one-off components
74+- **Layouts**: Separate layouts for different route groups
75+
76+#### Data Layer
77+
78+- **Server Actions**: Located in `/actions/` directory, organized by functionality
79+- **Services**: Located in `/lib/services/` directory for complex business logic
80+- **Database Schema**: Drizzle ORM schemas in `/db/schema/`
81+- **Type Safety**: Use schema-generated types like InsertProfile and SelectProfile from your database schemas
82+
83+#### Data Flow Architecture
84+
3585 Follow this layered architecture pattern:
86+
3687 - **React Components** → **Server Actions** → **Services** (when complex logic is needed)
3788 - Services handle domain-specific logic, external API integrations, and complex business rules
3889 - Keep Server Actions lightweight and focused on data validation and orchestration
3990
40−##### Server Components
91+#### Component Architecture
4192
42−- Use `"use server"` at the top of the file.
43−- Implement Suspense for asynchronous data fetching to show loading states while data is being fetched.
44−- If no asynchronous logic is required for a given server component, you do not need to wrap the component in `<Suspense>`. You can simply return the final UI directly since there is no async boundary needed.
45−- If asynchronous fetching is required, you can use a `<Suspense>` boundary and a fallback to indicate a loading state while data is loading.
46−- Server components cannot be imported into client components. If you want to use a server component in a client component, you must pass the as props using the "children" prop
47−- params in server pages should be awaited such as `const { courseId } = await params` where the type is `params: Promise<{ courseId: string }>`
93+- **UI Components**: Shadcn/UI components in `/components/ui/` (don't modify unless specified)
94+- **Shared Components**: Reusable components in `/components/`
95+- **Route-specific**: Components in `app/route/_components/`
4896
49−Example of a server layout:
97+## Important Development Rules
5098
51−```tsx
52−"use server"
99+### Environment Variables
53100
54−export default async function ExampleServerLayout({
55− children
56−}: {
57− children: React.ReactNode
58−}) {
59− return children
60−}
61−```
101+- Always use centralized config: `serverConfig` and `publicEnv` from `@/lib/config`
102+- Never use `process.env` directly in application code
103+- Update `.env.example` when adding new environment variables
62104
63−Example of a server page (with async logic):
105+### Import Conventions
64106
65−```tsx
66−"use server"
107+- Use `@/` for all imports from the app root
108+- Import types from `@/types`
109+- Import database types from `@/db/schema`
110+- Import services from `@/lib/services`
67111
68−import { Suspense } from "react"
69−import { SomeAction } from "@/actions/some-actions"
70−import SomeComponent from "./_components/some-component"
71−import SomeSkeleton from "./_components/some-skeleton"
112+### File Naming
72113
73−export default async function ExampleServerPage() {
74− return (
75− <Suspense fallback={<SomeSkeleton className="some-class" />}>
76− <SomeComponentFetcher />
77− </Suspense>
114+- Use kebab-case for all files and folders
115+- Type files: `example-types.ts` in `/types/` directory
116+- Export all types in `types/index.ts`
117+
118+### Code Quality Requirements
119+
120+- **Always use the correct Node.js version (20.12.2)** before running any code quality commands
121+- **Load nvm first**: Run the nvm commands above if you're in a new terminal session
122+- Run `yarn clean` after making changes to ensure code quality
123+- Use TypeScript interfaces over type aliases when possible
124+- Follow the existing patterns in the codebase
125+
126+## Coding Standards
127+
128+All code must adhere to these strict formatting and quality guidelines:
129+
130+### Syntax & Structure
131+
132+- File names must be dash-case (word-cloud.service.ts) unless an existing pattern differs
133+- Group imports: node/standard → npm packages → internal paths. No unused imports
134+- Use arrow functions everywhere except inside class bodies, where concise method syntax is allowed
135+- Prefer early returns; nested if/else blocks deeper than two levels are disallowed
136+- Early returns must use block format with braces (e.g., `if (!value) { return }`) for readability
137+- Extract function call results as scope variables before using in conditions (e.g., `const trimmedText = text.trim(); if (!trimmedText) {...}` instead of `if (!text.trim()) {...}`)
138+- Use async/await—never chain .then()
139+- No .forEach for side effects; use for (const x of arr) instead
140+- Array combinators (map, reduce, filter) are allowed only when you return their result
141+- Identifiers must be English
142+- No commented code allowed
143+
144+### Functional Programming Rules
145+
146+Each function must:
147+
148+- Be ≤ 50 lines (preferably; extract helpers if longer)
149+- Take ≤ 4 parameters (optional ones last)
150+- Have a single responsibility
151+- Be pure unless it is an intentional I/O wrapper (e.g. DB write); such wrappers must be ≤ 15 lines
152+- Name functions with camelCase imperative verbs (calculateTotals, getUserById)
153+
154+### Type Safety & Error Handling
155+
156+- Explicitly type all function parameters, return types, and exported constants
157+- Type all local variables inside a function
158+- **Special attention for async operations**: Variables from awaited functions (e.g., `const { userId } = await auth()`) must be explicitly typed, especially in Next.js components where auth results should use proper domain types
159+- No any; if an external library forces it, wrap and narrow
160+- Error handling in catch blocks:
161+ - If the error variable is not used, use `catch {}` (no parameter)
162+ - If the error is used, type it as `unknown` and handle it safely within the catch block
163+
164+### React Component Standards
165+
166+- Always define props with interfaces, never inline types
167+- Place interfaces directly above component definitions
168+- Use const arrow functions for component definitions
169+- Use implicit return syntax when components only return JSX (no logic before return)
170+- Export components using export default pattern (required for Next.js pages/layouts)
171+- Handler functions inside components must be ≤ 20 lines and have a single, clear responsibility. Extract helper functions for complex logic.
172+
173+ **Wrong (~50 lines in one handler):**
174+
175+ ```tsx
176+ const handleFormSubmit = async (): Promise<void> => {
177+ const trimmedName: string = formData.name.trim()
178+ const trimmedEmail: string = formData.email.trim()
179+ const trimmedMessage: string = formData.message.trim()
180+
181+ if (!trimmedName) {
182+ setErrors({ ...errors, name: "Name is required" })
183+ toast({
184+ title: "Error",
185+ description: "Name is required",
186+ variant: "destructive"
187+ })
188+ return
189+ }
190+
191+ if (!trimmedEmail || !trimmedEmail.includes("@")) {
192+ setErrors({ ...errors, email: "Valid email is required" })
193+ toast({
194+ title: "Error",
195+ description: "Valid email is required",
196+ variant: "destructive"
197+ })
198+ return
199+ }
200+
201+ if (!trimmedMessage || trimmedMessage.length < 10) {
202+ setErrors({
203+ ...errors,
204+ message: "Message must be at least 10 characters"
205+ })
206+ toast({
207+ title: "Error",
208+ description: "Message too short",
209+ variant: "destructive"
210+ })
211+ return
212+ }
213+
214+ setIsSubmitting(true)
215+ setErrors({})
216+
217+ try {
218+ const payload: FormPayload = {
219+ name: trimmedName,
220+ email: trimmedEmail,
221+ message: trimmedMessage,
222+ timestamp: new Date().toISOString()
223+ }
224+
225+ const response: Response = await fetch("/api/contact", {
226+ method: "POST",
227+ headers: { "Content-Type": "application/json" },
228+ body: JSON.stringify(payload)
229+ })
230+
231+ if (!response.ok) {
232+ throw new Error("Failed to submit")
233+ }
234+
235+ const result: SubmissionResult = await response.json()
236+
237+ setFormData({ name: "", email: "", message: "" })
238+ setSubmissionCount((prev) => prev + 1)
239+
240+ toast({ title: "Success", description: "Message sent successfully!" })
241+
242+ if (onSuccess) {
243+ onSuccess(result)
244+ }
245+ } catch (error: unknown) {
246+ const errorMessage: string =
247+ error instanceof Error ? error.message : "Unknown error"
248+ console.error("Submission error:", errorMessage)
249+ setErrors({ submit: "Failed to send message" })
250+ toast({
251+ title: "Error",
252+ description: "Failed to send message",
253+ variant: "destructive"
254+ })
255+ } finally {
256+ setIsSubmitting(false)
257+ }
258+ }
259+ ```
260+
261+ **Good (broken into focused helpers ≤ 20 lines each):**
262+
263+ ```tsx
264+ const validateForm = (): boolean => {
265+ const trimmedName: string = formData.name.trim()
266+ const trimmedEmail: string = formData.email.trim()
267+ const trimmedMessage: string = formData.message.trim()
268+
269+ if (!trimmedName) {
270+ setErrors({ ...errors, name: "Name is required" })
271+ toast({
272+ title: "Error",
273+ description: "Name is required",
274+ variant: "destructive"
275+ })
276+ return false
277+ }
278+
279+ if (!trimmedEmail || !trimmedEmail.includes("@")) {
280+ setErrors({ ...errors, email: "Valid email is required" })
281+ toast({
282+ title: "Error",
283+ description: "Valid email is required",
284+ variant: "destructive"
285+ })
286+ return false
287+ }
288+
289+ if (!trimmedMessage || trimmedMessage.length < 10) {
290+ setErrors({
291+ ...errors,
292+ message: "Message must be at least 10 characters"
293+ })
294+ toast({
295+ title: "Error",
296+ description: "Message too short",
297+ variant: "destructive"
298+ })
299+ return false
300+ }
301+
302+ return true
303+ }
304+
305+ const submitForm = async (): Promise<SubmissionResult> => {
306+ const payload: FormPayload = {
307+ name: formData.name.trim(),
308+ email: formData.email.trim(),
309+ message: formData.message.trim(),
310+ timestamp: new Date().toISOString()
311+ }
312+
313+ const response: Response = await fetch("/api/contact", {
314+ method: "POST",
315+ headers: { "Content-Type": "application/json" },
316+ body: JSON.stringify(payload)
317+ })
318+
319+ if (!response.ok) {
320+ throw new Error("Failed to submit")
321+ }
322+
323+ return response.json()
324+ }
325+
326+ const handleSuccess = (result: SubmissionResult): void => {
327+ setFormData({ name: "", email: "", message: "" })
328+ setSubmissionCount((prev: number) => prev + 1)
329+ toast({ title: "Success", description: "Message sent successfully!" })
330+
331+ if (onSuccess) {
332+ onSuccess(result)
333+ }
334+ }
335+
336+ const handleError = (error: unknown): void => {
337+ const errorMessage: string =
338+ error instanceof Error ? error.message : "Unknown error"
339+ console.error("Submission error:", errorMessage)
340+ setErrors({ submit: "Failed to send message" })
341+ toast({
342+ title: "Error",
343+ description: "Failed to send message",
344+ variant: "destructive"
345+ })
346+ }
347+
348+ const handleFormSubmit = async (): Promise<void> => {
349+ const isValid: boolean = validateForm()
350+
351+ if (!isValid) {
352+ return
353+ }
354+
355+ setIsSubmitting(true)
356+ setErrors({})
357+
358+ try {
359+ const result: SubmissionResult = await submitForm()
360+ handleSuccess(result)
361+ } catch (error: unknown) {
362+ handleError(error)
363+ } finally {
364+ setIsSubmitting(false)
365+ }
366+ }
367+ ```
368+
369+- Example with implicit return:
370+
371+ ```tsx
372+ interface MyComponentProps {
373+ title: string
374+ children: React.ReactNode
375+ }
376+
377+ const MyComponent = ({ title, children }: MyComponentProps) => (
378+ <div>
379+ {title}
380+ {children}
381+ </div>
78382 )
79−}
80383
81−async function SomeComponentFetcher() {
82− const { data } = await SomeAction()
83− return <SomeComponent className="some-class" initialData={data || []} />
84−}
85−```
384+ export default MyComponent
385+ ```
86386
87−Example of a server page (no async logic required):
387+- Example with explicit return (when logic is present):
88388
89−```tsx
90−"use server"
389+ ```tsx
390+ interface MyComponentProps {
391+ title: string
392+ children: React.ReactNode
393+ }
91394
92−import SomeClientComponent from "./_components/some-client-component"
395+ const MyComponent = ({ title, children }: MyComponentProps) => {
396+ const processedTitle = title.toUpperCase()
93397
94−// In this case, no asynchronous work is being done, so no Suspense or fallback is required.
95−export default async function ExampleServerPage() {
96− return <SomeClientComponent initialData={[]} />
97−}
98−```
398+ return (
399+ <div>
400+ {processedTitle}
401+ {children}
402+ </div>
403+ )
404+ }
99405
100−Example of a server component:
406+ export default MyComponent
407+ ```
101408
102−```tsx
103−"use server"
409+- Normal components that are not Next.js pages/layouts should be exported
410+ using export const pattern
411+- Example with implicit return:
104412
105−interface ExampleServerComponentProps {
106− // Your props here
107−}
413+ ```tsx
414+ interface NotAPageOrLayoutComponentProps {
415+ title: string
416+ children: React.ReactNode
417+ }
108418
109−export async function ExampleServerComponent({
110− props
111−}: ExampleServerComponentProps) {
112− // Your code here
113−}
114−```
419+ export const NotAPageOrLayoutComponent = ({
420+ title,
421+ children
422+ }: NotAPageOrLayoutComponentProps) => (
423+ <div>
424+ {title}
425+ {children}
426+ </div>
427+ )
428+ ```
115429
116−##### Client Components
430+### Component Granularity & Organization
117431
118−- Use `"use client"` at the top of the file
119−- Client components can safely rely on props passed down from server components, or handle UI interactions without needing <Suspense> if there’s no async logic.
120−- Never use server actions in client components. If you need to create a new server action, create it in `/actions`
432+- Break down large components into smaller, focused components for better maintainability
433+- When a component contains multiple logical sections (e.g., Card with CardHeader + CardContent), extract each section into separate components
434+- Create dedicated folders for related component groups:
435+ - Use kebab-case folder names matching the main component concept
436+ - Place related sub-components within the same folder using kebab-case file names
437+ - Example structure: `component-name/component-name-header.tsx`, `component-name/component-name-content.tsx`
438+- Each sub-component should have a single, clear responsibility
439+- Maintain the parent component as a composition wrapper that orchestrates child components
440+- Follow this pattern when refactoring existing components or creating new feature components
121441
122−Example of a client page:
442+### Advanced Component Architecture Patterns
123443
124−```tsx
125−"use client"
444+#### Pure Functions and Constants Organization
126445
127−export default function ExampleClientPage() {
128− // Your code here
129−}
130−```
446+- **Pure functions** (no side effects, deterministic output) must be extracted outside components:
447+ - Place above the component definition
448+ - Examples: `getGreeting()`, `getMembershipBadgeColor()`, `formatDate()`
449+- **Constants and static data** must be moved outside components:
450+ - Place after imports and interfaces, before pure functions
451+ - Use SCREAMING_SNAKE_CASE for naming (e.g., `TEMPLATE_FEATURES`, `TECH_STACK`) constants
452+ - **Always explicitly type constants** with appropriate type annotations
453+ - Examples: `const API_URL: string = "..."`, `const MAX_RETRIES: number = 3`
454+ - Use `as const` for immutable values when type inference is sufficient
455+ - Group related constants together
131456
132−Example of a client component:
457+#### Custom Hooks Organization
133458
134−```tsx
135−"use client"
459+- **Custom hooks** must be extracted to separate files in the `/hooks/` directory:
460+ - Use kebab-case file naming: `use-scroll-detection.ts`, `use-local-storage.ts`
461+ - Start hook names with `use` prefix following React conventions
462+ - Place hooks in `/hooks/` folder at project root level
463+ - Export hooks using named exports: `export const useScrollDetection = () => {}`
464+ - **Always explicitly type hook return values** and parameters
465+ - Examples: `useScrollDetection(): boolean`, `useLocalStorage<T>(key: string): [T, (value: T) => void]`
466+ - Group related hooks in the same file only if they're tightly coupled
136467
137−interface ExampleClientComponentProps {
138− initialData: any[]
139−}
468+#### Whitespace and Formatting Rules
140469
141−export default function ExampleClientComponent({
142− initialData
143−}: ExampleClientComponentProps) {
144− // Client-side logic here
145− return <div>{initialData.length} items</div>
146−}
470+- **Component variable organization**: Maintain consistent whitespace between different types of declarations:
471+ - Add a blank line between React state declarations and custom hook calls
472+ - Add a blank line between custom hook calls and other variable declarations
473+ - Example:
474+
475+ ```tsx
476+ const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false)
477+ const [isVisible, setIsVisible] = useState<boolean>(true)
478+
479+ const isScrolled: boolean = useScrollDetection()
480+ const userData: UserData = useUserData()
481+
482+ const processedData: ProcessedData = processUserData(userData)
483+ ```
484+
485+#### Nested Component Structure for Complex Components
486+
487+When a component has multiple distinct sections, create nested folder structure:
488+
147489 ```
490+dashboard-welcome/
491+├── dashboard-welcome.tsx // Main orchestrator component
492+├── greeting.tsx // Self-contained greeting section
493+├── whats-included/ // Folder for multi-part section
494+│ ├── whats-included.tsx // Section orchestrator
495+│ ├── whats-included-title.tsx // Title sub-component
496+│ └── whats-included-features.tsx // Features list sub-component
497+├── core-technologies/ // Folder for multi-part section
498+│ ├── core-technologies.tsx // Section orchestrator
499+│ ├── core-technologies-title.tsx // Title sub-component
500+│ └── core-technologies-list.tsx // Tech list sub-component
501+└── get-started/ // Folder for multi-part section
502+ ├── get-started.tsx // Section orchestrator
503+ ├── get-started-title.tsx // Title sub-component
504+ ├── get-started-features.tsx // Features grid sub-component
505+ └── get-started-feature-2.tsx // Individual feature card
506+```
507+
508+#### Component Organization Rules
509+
510+1. **Main orchestrator**: Composition only, minimal logic, imports and renders sub-components
511+2. **Section orchestrators**: Handle section-specific logic, render related sub-components
512+3. **Leaf components**: Single responsibility, pure presentation, accept props only
513+4. **Shared constants**: Extract to file level, use proper naming conventions
514+5. **Pure functions**: Extract above component definitions, properly typed
515+6. **File structure**: Mirror logical component hierarchy in folder structure
516+
517+### Application Guidelines
518+
519+1. Apply these standards to all new code and when refactoring existing code
520+2. When making any code changes, ensure they conform to these guidelines
521+3. If existing code doesn't follow these standards, update it to comply when modifying those files
522+4. Use these standards as a checklist when reviewing code changes
523+5. Prefer extracting helper functions over writing long, complex functions
524+6. Always prioritize code readability and maintainability
525+
526+## Database Schema
527+
528+### Current Tables
529+
530+- **Profiles**: User profiles with Stripe integration and membership tiers
531+
532+### Schema Location
533+
534+- Schemas: `/db/schema/`
535+- Migrations: `/db/migrations/`
536+- Database connection: `/db/db.ts`
537+
538+## Testing and Deployment
539+
540+- The project uses Vercel for deployment
541+- No specific test framework is configured - check with user if testing is needed
542+- Always run `yarn build` and `yarn type-check` before considering work complete
543+
