Next.js 14 Fitness App - Mobile-First Development Rules
A comprehensive set of development rules for building a mobile-first fitness intelligence app with Next.js 14, optimized for fast daily check-ins, workout logging, and analytics.
Tech Stack
**Framework**: Next.js 14+ (App Router)**Language**: TypeScript**Styling**: Tailwind CSS**Database**: PostgreSQL with Prisma ORM**Platform**: Mobile-first PWA**Pattern**: React Server Components + API RoutesProject Structure
```
app/
(routes)/ # Route groups
api/ # API routes (route.ts files)
components/ # Reusable components
ui/ # Base UI components
checkin/ # Feature-specific components
workout/
analytics/
lib/ # Utilities and shared code
db/ # Database utilities (Prisma)
services/ # Business logic
utils/ # Helper functions
types/ # TypeScript types
```
Core Development Principles
1. Next.js App Router Best Practices
Use Server Components by default; only use Client Components when necessary for interactivityImplement file-based routing with `app/` directory structureUse `layout.tsx` for shared layouts with nested layouts for route groupsImplement `loading.tsx` for automatic Suspense boundariesUse `error.tsx` for route-level error boundariesUtilize route handlers (`route.ts`) for API routes, not Pages Router patternsExport metadata from page/layout files using the metadata APIUse Next.js Image component for optimized image loading with WebP supportStore configuration in `.env.local` environment variables2. TypeScript Standards
Use TypeScript for all code; prefer interfaces over typesAvoid enums; use maps or const objects insteadUse functional components with TypeScript interfacesNever use `any`; use `unknown` with proper type guards if neededLeverage Prisma-generated types for database type safetyUse Zod for runtime validation on forms and API boundaries3. Component Patterns
**Component Definition Syntax:**
```tsx
// Server Component (default)
export const ComponentName = () => {
// Component logic
};
// Client Component (when needed)
'use client'
interface ComponentNameProps {
prop1: string;
prop2: number;
}
export const ComponentName = ({ prop1, prop2 }: ComponentNameProps) => {
// Component logic
};
// Page components use default exports
const Page = () => {
// Page logic
};
export default Page;
```
**File Organization Order:**
1. Exported component
2. Subcomponents
3. Helper functions
4. Static content
5. Types/interfaces
**Naming Conventions:**
Components: PascalCase (`CheckinForm.tsx`)Utilities: camelCase (`formatDate.ts`)Constants: UPPER_SNAKE_CASE (`API_ENDPOINTS.ts`)Types/Interfaces: PascalCase (`WorkoutData.ts`)Directories: lowercase with dashes (`components/auth-wizard/`)API routes: `route.ts` (lowercase)Favor named exports for components4. Code Style
Write concise, technical TypeScript code with accurate examplesUse functional and declarative programming patterns; avoid classesPrefer iteration and modularization over code duplicationUse descriptive variable names with auxiliary verbs (`isLoading`, `hasError`)Use the "function" keyword for pure functionsAvoid unnecessary curly braces in conditionals; use concise syntaxUse declarative JSXMinimize AI-generated comments; use clearly named variables and functions5. Error Handling and Validation
Prioritize error handling; handle errors and edge cases earlyUse early returns and guard clausesImplement proper error logging with user-friendly messagesUse Zod for form validation with type-safe schemasModel expected errors as return values in Server ActionsUse error boundaries (`error.tsx`) for unexpected errorsNever expose sensitive error details to clientUse consistent error response format in API routes**Error Boundary Pattern:**
```tsx
'use client'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
```
6. Mobile-First UI and Styling
Use Tailwind CSS exclusively for styling; avoid inline stylesMobile-first approach: base styles for mobile, then `md:`, `lg:` breakpointsEnsure touch targets are at least 44x44px for mobileUse consistent spacing scale from TailwindTest on mobile viewport sizes regularlyImplement responsive design with Tailwind CSS breakpointsUse semantic HTML for accessibilityInclude ARIA labels where neededEnsure keyboard navigation worksMaintain proper heading hierarchyProvide alt text for imagesEnsure sufficient color contrast7. Mobile-First Development Focus
Always consider mobile viewport first with mobile-first CSSTest interactions with touch in mind; use large touch targetsEnsure forms are easy to complete on mobileMinimize typing requirements; use dropdowns, buttons, slidersConsider one-handed usage; place primary actions in thumb zoneOptimize for fast data entry (primary focus of this app)8. Data Ingestion Optimization
Optimize for fast data entry; minimize form fieldsUse smart defaults; pre-fill when possibleAuto-save when possible to reduce data loss riskProvide clear validation feedback with real-time validationSupport offline entry with IndexedDB + background syncMinimize text input; use buttons, sliders, selectorsDesign for fast form completion with vertical flow and clear progression9. Performance Optimization
Minimize `useEffect` and `setState`; favor React Server Components (RSC)Wrap client components in Suspense with fallbackUse dynamic loading for non-critical componentsOptimize images: WebP format, include size data, implement lazy loadingUse Next.js built-in caching with `fetch` and `next: { revalidate }` optionOptimize database queries; avoid N+1 queries, use Prisma efficientlyCache API responses when appropriateImplement proper loading states with `loading.tsx` files10. Data Fetching Patterns
**Server Components (Preferred):**
```tsx
async function getData() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 }
})
if (!res.ok) throw new Error('Failed to fetch data')
return res.json()
}
export default async function Page() {
const data = await getData()
// Render component
}
```
**API Routes:**
```tsx
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
return NextResponse.json({ data: 'example' })
}
export async function POST(request: NextRequest) {
const body = await request.json()
// Validate with Zod
return NextResponse.json({ success: true })
}
```
11. Database and Prisma Patterns
Always use Prisma Client for database access; avoid raw SQL unless absolutely necessaryUse transactions (`prisma.$transaction()`) for multi-step operationsHandle database errors gracefully with proper try-catch blocksIndex frequently queried fields; optimize for common queriesUse Prisma-generated types for type safetyPrisma automatically handles parameterized queriesDesign for time-series queries (workout history, trends, analytics)12. API Route Patterns
Use Next.js route handlers (`route.ts` files in `app/api/`)Validate all inputs with Zod schemas for type-safe validationReturn consistent error response formatUse proper HTTP status codes (200, 201, 400, 401, 404, 500)Handle errors with try-catch blocksLog errors appropriately for debuggingAlways authenticate requests except public routesUse HTTP-only cookies for sessionsProtect API routes with authentication middleware13. Security
Validate all user inputs with Zod schemasSanitize data before database operations (Prisma handles SQL injection)Implement proper authentication checks with session-based authUse HTTP-only cookies for sessions (XSS protection)Protect API routes with authentication middlewareNever expose sensitive error details to clientUse environment variables for secrets and configuration14. PWA Implementation
Implement Service Worker for offline workout loggingUse IndexedDB for local storage during offline periodsImplement background sync for uploading when connection restoredCreate PWA manifest with app name, icons, theme colors, standalone modeUse offline-first approach (critical for gym environments)15. React Server Components Guidelines
Favor server components and Next.js SSRUse client components only for: - Web API access (localStorage, window, etc.)
- Interactivity (onClick, onChange, etc.)
- Browser-only features
Avoid client components for: - Data fetching (use Server Components)
- State management (use Server Components + URL state)
Mark client components with `'use client'` directive at top of file16. Code Organization
Follow atomic design principles: atoms → molecules → organisms → templates → pagesPlace components in `components/` directoryGroup related components in subdirectories (`components/checkin/`, `components/workout/`)Co-locate component files with related utilities when appropriateUse index files for clean imports when neededKeep components small and focusedUse composition over inheritanceExtract reusable logic to custom hooks when needed17. Metadata and SEO
```tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Page Title',
description: 'Page description',
}
```
Key Conventions
Use proper URL search parameter state managementOptimize Web Vitals (LCP, CLS, FID)Limit `'use client'` usage; prefer Server ComponentsFollow Next.js 14 App Router docs for Data Fetching, Rendering, and RoutingUse functional components exclusivelyWrite testable code with pure functions where possibleExtract business logic from componentsComment complex business logicDocument API endpoints with inline comments or JSDocAI Interaction Guidelines
When generating code, prioritize TypeScript and React best practicesEnsure new components are reusable and follow existing design patternsAlways validate user inputs and handle errors gracefullyUse existing components and pages as referencePrefer existing patterns over new approachesAsk for clarification if requirements are unclearSuggest improvements if a better pattern existsMaintain consistency with existing codebaseImportant Scripts
`dev`: Start development server`build`: Build for production`start`: Start production server`lint`: Run ESLint`type-check`: Run TypeScript type checkingAdditional Resources
[Next.js Documentation](https://nextjs.org/docs)[TypeScript Handbook](https://www.typescriptlang.org/docs/)[Tailwind CSS Documentation](https://tailwindcss.com/docs)[React Documentation](https://react.dev/)[Prisma Documentation](https://www.prisma.io/docs)