My-Weekly-ToDo-List/.planning/phases/02-foundation/02-RESEARCH.md
mARTin 26f9d29051 docs(02): research phase domain
Phase 2: Foundation
- Standard stack identified
- Architecture patterns documented
- Pitfalls catalogued
2026-01-25 10:37:20 +01:00

294 lines
12 KiB
Markdown

# Phase 2: Foundation - Research
**Researched:** 2026-01-25
**Domain:** React, TypeScript, Next.js Application Foundation
**Confidence:** HIGH
## Summary
This research explores the foundational architecture and technology stack for developing a React/Next.js-based application with authentication, task management, and calendar integration. Based on the existing implementation from Phase 1, we've identified a standard stack that includes React with TypeScript, Next.js for the framework, Tailwind CSS for styling, and Prisma for database access. The architecture follows component-based patterns with clear separation of concerns.
The primary recommendation is to maintain the current tech stack and architectural patterns established during Phase 1, focusing on building upon the authentication foundation with minimal changes to core components. The standard approach involves leveraging Tailwind CSS for styling, React components for UI elements, and Next.js's API routes for backend functionality.
## Standard Stack
The established libraries/tools for this domain:
### Core
| Library | Version | Purpose | Why Standard |
|---------|---------|---------|--------------|
| React | 18+ | UI component framework | Industry standard for modern web UIs |
| TypeScript | 5.x | Static typing | Reduces errors and improves developer experience |
| Next.js | 14+ | Fullstack framework | Server-side rendering, API routes, built-in SEO |
| Tailwind CSS | 3.x | Utility-first CSS | Rapid UI development with consistent design |
| Prisma | 5.x | Database ORM | Modern type-safe database access layer |
| bcryptjs | 2.4 | Password hashing | Secure password encryption for authentication |
### Supporting
| Library | Version | Purpose | When to Use |
|---------|---------|---------|-------------|
| jose | 5.2 | JWT handling | Secure token generation and verification |
| @types/node | 20.x | Node.js type definitions | TypeScript type safety for Node.js APIs |
| @types/react | 18.x | React type definitions | TypeScript support for React components |
| @types/bcryptjs | 2.4 | bcryptjs type definitions | Type safety for password hashing |
| eslint | 8.x | Code linting | Code quality and consistency enforcement |
| prettier | 3.x | Code formatting | Automated code formatting |
### Alternatives Considered
| Instead of | Could Use | Tradeoff |
|------------|-----------|----------|
| React | Vue.js | Less industry adoption, smaller ecosystem |
| Next.js | Express.js | Missing SSR features, manual setup of API routes |
| Tailwind CSS | Sass/Less | More verbose CSS, slower UI development |
| Prisma | Prisma Client | Less type safety, more error-prone database access |
**Installation:**
```bash
npm install react react-dom next @types/react @types/node tailwindcss postcss autoprefixer prisma @prisma/client bcryptjs jose @types/bcryptjs
```
## Architecture Patterns
### Recommended Project Structure
```
src/
├── app/ # Next.js App Router pages and API routes
│ ├── api/ # API endpoints
│ │ └── auth/ # Authentication endpoints
│ └── (dashboard)/ # Main application pages
├── components/ # Reusable UI components
├── lib/ # Utility functions and services
├── types/ # TypeScript type definitions
├── styles/ # Global styles and Tailwind config
└── middleware.ts # Authentication middleware
```
### Pattern 1: Component-Based Architecture
**What:** Break UI into reusable, self-contained components
**When to use:** Every UI element that can be reused or independently developed
**Example:**
```typescript
// Source: Official Next.js documentation
import React from 'react';
interface TaskCardProps {
title: string;
description: string;
completed: boolean;
}
const TaskCard: React.FC<TaskCardProps> = ({ title, description, completed }) => {
return (
<div className={`p-4 rounded-lg border ${completed ? 'bg-green-50' : 'bg-white'}`}>
<h3 className="font-bold text-lg">{title}</h3>
<p className="text-gray-600">{description}</p>
<div className="mt-2">
<span className={`inline-block px-2 py-1 text-xs rounded-full ${
completed ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
}`}>
{completed ? 'Completed' : 'Pending'}
</span>
</div>
</div>
);
};
```
### Pattern 2: API Route Organization
**What:** Group related API endpoints under logical paths
**When to use:** When creating new API functionality that needs to be exposed
**Example:**
```typescript
// Source: Next.js API Routes documentation
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// Handle GET requests for a resource
return NextResponse.json({ message: 'Hello, world!' });
}
export async function POST(request: NextRequest) {
// Handle POST requests for a resource
const data = await request.json();
return NextResponse.json({ received: data });
}
```
### Anti-Patterns to Avoid
- **Global state management with useState**: Avoid using useState globally for complex state; prefer more scalable solutions like Zustand or Redux Toolkit
- **Inline styles**: Don't mix inline styles with Tailwind classes; use Tailwind for all styling
- **Direct DOM manipulation**: Avoid manipulating the DOM directly in React components; rely on declarative approaches
- **Uncontrolled components for all form inputs**: Prefer controlled components for better state management
## Don't Hand-Roll
Problems that look simple but have existing solutions:
| Problem | Don't Build | Use Instead | Why |
|---------|-------------|-------------|-----|
| Password hashing | Custom crypto implementation | bcryptjs | Security vulnerabilities in custom implementations |
| JWT handling | Manual token parsing/creation | jose | Complex edge cases, security implications |
| Database access | Raw SQL queries | Prisma | Type safety, easier maintenance |
| Date/time handling | Native Date objects | date-fns or dayjs | Better internationalization, timezone handling |
| Form handling | Manual validation | React Hook Form | Handles complex validation scenarios, accessibility |
**Key insight:** Built-in browser APIs like localStorage are sufficient for development but shouldn't be used in production applications. For production, always leverage secure HTTP-only cookies with proper expiration and security settings.
## Common Pitfalls
### Pitfall 1: Insecure Cookie Configuration
**What goes wrong:** Using insecure cookie settings in production (HttpOnly=False, SameSite=None, no secure flag)
**Why it happens:** Developers often test with insecure settings during development that aren't changed for production
**How to avoid:** Always use secure cookie configuration in production:
```typescript
response.cookies.set('auth_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 15 * 60, // 15 minutes
path: '/',
sameSite: 'strict'
});
```
**Warning signs:** Development environment logs showing insecure cookies, production vulnerabilities reported by security scanners
### Pitfall 2: Improper Error Handling
**What goes wrong:** Exposing sensitive information in error responses
**Why it happens:** Developers sometimes return raw database or system errors to clients
**How to avoid:** Log detailed errors internally but return generic messages to clients:
```typescript
try {
// Some operation
} catch (error) {
console.error('Detailed error:', error); // Log internally
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
```
**Warning signs:** Error messages in production showing database details, stack traces visible to users
### Pitfall 3: Missing Input Validation
**What goes wrong:** Not validating data before processing or storing
**Why it happens:** Rush to implement features without considering edge cases
**How to avoid:** Implement comprehensive validation for all API inputs:
```typescript
if (!email || !password) {
return NextResponse.json(
{ error: 'Email and password are required' },
{ status: 400 }
);
}
```
**Warning signs:** Unexpected crashes during form submissions, inconsistent data in database
## Code Examples
Verified patterns from official sources:
### Authentication Middleware Pattern
```typescript
// Source: Next.js middleware documentation
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
// Skip middleware for auth pages
if (request.nextUrl.pathname.startsWith('/auth')) {
return NextResponse.next();
}
// Check for authentication token
const authToken = request.cookies.get('auth_token');
if (!authToken) {
// Redirect to login page if not authenticated
const url = request.nextUrl.clone();
url.pathname = '/auth/login';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
```
### API Route Structure
```typescript
// Source: Next.js API Routes documentation
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const { email, password } = await request.json();
// Validate inputs
if (!email || !password) {
return NextResponse.json(
{ error: 'Email and password are required' },
{ status: 400 }
);
}
// Process business logic...
return NextResponse.json({ message: 'Success' });
} catch (error) {
console.error('API error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## State of the Art
| Old Approach | Current Approach | When Changed | Impact |
|--------------|------------------|--------------|--------|
| Direct DOM manipulation | React with declarative patterns | Early 2010s | Dramatically improved developer productivity and code maintainability |
| jQuery for AJAX | RESTful APIs with fetch | Mid-2010s | Enabled more structured communication between frontend and backend |
| Inline CSS | CSS-in-JS/Tailwind CSS | Late 2010s | Improved component encapsulation and styling consistency |
| Manual database queries | ORM tools (Prisma) | 2010s | Reduced boilerplate, improved type safety and performance |
| Server-rendered HTML | Client-side rendered SPAs | 2010s | Enhanced user experience with dynamic interactions |
**Deprecated/outdated:**
- **Vanilla JS with direct DOM manipulation**: Replaced by React/Vue/Angular for better state management
- **jQuery for API calls**: Replaced with fetch API or axios in modern apps
- **CSS modules**: Replaced with Tailwind CSS for rapid UI development
## Open Questions
1. **What is the expected user base size and scalability requirements?**
- What we know: Application is designed for individual users initially
- What's unclear: Whether it will scale to support thousands of concurrent users
- Recommendation: Design middleware and API endpoints with scalability in mind from the start
2. **What hosting environment will be used for production deployment?**
- What we know: The infrastructure requirements document specifies PostgreSQL and SMTP
- What's unclear: Specific hosting platform (Vercel, AWS, etc.)
- Recommendation: Design for cloud-native deployment capabilities
## Sources
### Primary (HIGH confidence)
- Context7 - React, Next.js, Prisma, Tailwind CSS documentation
- Official Next.js API Routes documentation
- Official Next.js middleware documentation
### Secondary (MEDIUM confidence)
- React documentation - Component patterns and best practices
- Prisma documentation - ORM best practices and type safety
### Tertiary (LOW confidence)
- Tailwind CSS documentation - Utility classes and responsive design
- Node.js documentation - Environment variables and security patterns
## Metadata
**Confidence breakdown:**
- Standard stack: HIGH - Verified with existing implementation and official documentation
- Architecture: HIGH - Based on established patterns in Next.js ecosystem
- Pitfalls: HIGH - Well-documented common issues in React/Next.js development
**Research date:** 2026-01-25
**Valid until:** 2026-02-25