refactor: rebuild template — Tailwind v4, Docker self-hosting, passkey auth

Toolchain fixes (all previously broken):
- npm run lint: next lint was removed in Next 16 -> eslint with flat config
- .eslintrc.json was ignored by ESLint 9 -> eslint.config.mjs
- npm test / test:e2e exited 1 with no tests -> passWithNoTests
- Vitest scanned tests/ and would have run Playwright specs -> scoped to src/
- Playwright targeted Mobile Safari while docs installed only chromium
- reuseExistingServer silently tested a foreign server on :3000 -> E2E_PORT
- 11 high-severity vulns -> npm audit fix
- deny rule Read(**/.env*) also blocked .env.example -> precise patterns

Stack changes:
- Tailwind v3 -> v4 (CSS-first, no tailwind.config.ts, tw-animate-css)
- shadcn regenerated for v4; 33 components -> 6 core, bundled radix-ui
- Supabase removed entirely; data layer is now chosen per project
- Vercel removed; Docker Compose self-hosting with scripts/update.sh
- Better Auth + passkey plugin as the binding auth standard
- ThemeProvider and Sonner mounted; dark mode and toasts now actually work

Workflow system:
- Sub-agents wired: /frontend, /backend, /qa delegate to .claude/agents
- Checklists folded into their SKILL.md; one file per skill
- Rules rewritten: DB-agnostic backend, passkey security, v4 frontend
- Spec language settled as German, skill instructions English
This commit is contained in:
Florian Wilde
2026-08-09 00:48:50 +02:00
parent a8b196e92b
commit b0c4e9e9b9
101 changed files with 3651 additions and 7695 deletions
+148
View File
@@ -0,0 +1,148 @@
# Deployment
Self-hosted Docker Compose. One app container, published on loopback; a reverse
proxy already running on the host terminates TLS and forwards to it.
## Files
| File | Purpose |
|------|---------|
| `Dockerfile` | Three-stage build → Next.js standalone bundle, runs as an unprivileged user |
| `compose.yaml` | The `app` service, healthcheck, log rotation |
| `.dockerignore` | Keeps the build context small — no `node_modules`, no `.env`, no docs |
| `scripts/update.sh` | Pull, rebuild, restart, roll back if unhealthy |
| `.env.example` | Every variable the app needs, with dummy values |
## First deployment
Prerequisites on the server: Docker with the Compose plugin, a reverse proxy, and
a DNS record pointing at it.
```bash
git clone <repo-url> /srv/<app-name>
cd /srv/<app-name>
cp .env.example .env
```
Edit `.env`:
| Variable | Notes |
|----------|-------|
| `NEXT_PUBLIC_APP_URL` | The real public URL. With auth this **must** match the domain exactly — the WebAuthn relying-party ID is derived from it, and a mismatch breaks every passkey without a clear error. |
| `APP_PORT` | Host port the reverse proxy forwards to |
| `APP_BIND` | Leave at `127.0.0.1` unless the container must be publicly reachable |
| `BETTER_AUTH_SECRET` | `openssl rand -base64 32`, unique per environment |
```bash
docker compose up -d --build
curl -fsS http://127.0.0.1:3000/api/health # {"status":"ok"}
```
### Reverse proxy
Forward to `127.0.0.1:$APP_PORT` and pass through `X-Forwarded-Proto` and
`X-Forwarded-Host` — without them redirects and WebAuthn origin checks fail.
nginx:
```nginx
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```
Caddy:
```
app.example.com {
reverse_proxy 127.0.0.1:3000
}
```
Passkeys require HTTPS in production. Localhost is the only exemption.
## Updates
```bash
./scripts/update.sh # deploy the current branch's latest commit
./scripts/update.sh --force # rebuild even without a new commit
./scripts/update.sh --branch dev # deploy another branch
```
What it does: refuses to run on a dirty working tree, fast-forwards to
`origin/<branch>`, rebuilds, restarts, then polls the container healthcheck for up
to `HEALTH_TIMEOUT` seconds (default 120). If the container never turns healthy it
prints the last 50 log lines, resets to the previous commit, rebuilds and restarts
that — so a bad deploy self-heals instead of leaving the site down.
## Database
The template ships none by design. When `/architecture` picks one:
1. Add it as a second service in `compose.yaml` — no published port, reachable only
over the internal Compose network
2. Add a named volume for its data
3. Add `DATABASE_URL` to `.env.example`
4. Run migrations **before** the new container serves traffic. Either add a
short-lived `migrate` service that the app depends on, or add the migration
command to `scripts/update.sh` between build and restart.
5. Set up a backup for the volume — a volume is not a backup
## Operations
```bash
docker compose logs -f app # follow logs
docker compose ps # status incl. health
docker compose restart app # restart without rebuilding
docker compose down # stop the stack
docker compose exec app sh # shell inside the container
```
Logs rotate at 10 MB with 3 files kept, configured in `compose.yaml`.
## Manual rollback
```bash
git reset --hard <previous-sha>
docker compose up -d --build
```
## Security headers
Set in `next.config.ts`: `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`,
`Referrer-Policy: origin-when-cross-origin`, `Strict-Transport-Security`.
Verify after deploying that the proxy did not strip them: DevTools → Network →
pick a request → Response Headers.
A Content-Security-Policy is deliberately not preconfigured — it breaks apps when
guessed. Add it per project, starting with `Content-Security-Policy-Report-Only`.
## Error tracking
Not preinstalled. When you want it, Sentry is the usual choice:
```bash
npx @sentry/wizard@latest -i nextjs
```
It edits `next.config.ts` — re-check that the `headers()` block survived, and add
`SENTRY_DSN` to `.env.example`.
## Troubleshooting
| Symptom | Cause |
|---------|-------|
| Builds locally, fails in Docker | Build-time dependency sits in `devDependencies` |
| Env var undefined at runtime | Missing in the server's `.env`, or needs the `NEXT_PUBLIC_` prefix for client use |
| Container healthy, proxy returns 502 | Proxy points at the wrong port, or `APP_BIND` is not reachable from it |
| Redirect loop | Proxy not forwarding `X-Forwarded-Proto` |
| Passkeys fail after deploy | `NEXT_PUBLIC_APP_URL` mismatch, or no HTTPS |
| `update.sh` refuses to start | Uncommitted changes on the server — commit or discard them |
+19 -17
View File
@@ -1,29 +1,31 @@
# Product Requirements Document
## Vision
_Describe what you are building and why._
_Was wird gebaut und warum? Zwei bis drei Sätze._
## Target Users
_Who will use this product? Describe their needs and pain points._
## Zielgruppe
_Wer nutzt das Produkt? Welchen konkreten Schmerz hat diese Gruppe heute?_
## Core Features (Roadmap)
## Roadmap
| Priority | Feature | Status |
|----------|---------|--------|
| P0 (MVP) | _Feature 1_ | Planned |
| P0 (MVP) | _Feature 2_ | Planned |
| P1 | _Feature 3_ | Planned |
| P2 | _Feature 4_ | Planned |
| Priorität | Feature | Status |
|-----------|---------|--------|
| P0 (MVP) | _Feature 1_ | Roadmap |
| P0 (MVP) | _Feature 2_ | Roadmap |
| P1 | _Feature 3_ | Roadmap |
| P2 | _Feature 4_ | Roadmap |
## Success Metrics
_How will you measure success? (e.g., user signups, retention, task completion rate)_
## Erfolgsmetriken
_Woran wird gemessen, ob das Produkt funktioniert?_
## Constraints
_Budget, timeline, technical limitations, team size._
## Rahmenbedingungen
_Zeit, Budget, Teamgröße, technische Grenzen. Auch: Braucht das Projekt dauerhafte
Datenspeicherung? Braucht es Nutzerkonten?_
## Non-Goals
_What are you explicitly NOT building in this version?_
## Nicht-Ziele
_Was in dieser Version bewusst nicht gebaut wird._
---
Use `/requirements` to create detailed feature specifications for each item in the roadmap above.
Dieses Dokument füllt `/init` im Interview aus. Danach entstehen mit `/write-spec`
die einzelnen Feature-Specs.
-91
View File
@@ -1,91 +0,0 @@
# Database Optimization
## 1. Indexing
Create indexes on columns used in WHERE, ORDER BY, or JOIN clauses:
```sql
-- Without index: ~500ms at 100k rows
SELECT * FROM tasks WHERE user_id = 'abc123' ORDER BY created_at DESC;
-- After creating index: <10ms
CREATE INDEX idx_tasks_user_id_created ON tasks(user_id, created_at DESC);
```
**Rule of thumb:** If a column appears in WHERE or ORDER BY and the table will have >1000 rows, add an index.
Always include indexes in your migration SQL alongside CREATE TABLE.
## 2. Avoid N+1 Queries
The most common performance problem with ORMs and query builders:
```typescript
// Bad: N+1 (1 query for users + N queries for tasks)
const { data: users } = await supabase.from('users').select('*')
for (const user of users) {
const { data: tasks } = await supabase
.from('tasks')
.select('*')
.eq('user_id', user.id)
}
// Good: Single query with join (1 query total)
const { data } = await supabase
.from('users')
.select('*, tasks(*)')
```
## 3. Always Limit Results
Never return unbounded results from the database:
```typescript
// Bad: Returns ALL rows
const { data } = await supabase.from('tasks').select('*')
// Good: Returns max 50 rows
const { data } = await supabase.from('tasks').select('*').limit(50)
// Better: Paginated
const { data } = await supabase
.from('tasks')
.select('*')
.range(0, 49) // First 50 rows
```
## 4. Caching Strategy
For data that changes rarely (dashboard stats, config, categories):
```typescript
import { unstable_cache } from 'next/cache'
export const getCategories = unstable_cache(
async () => {
const { data } = await supabase.from('categories').select('*')
return data
},
['categories'], // Cache key
{ revalidate: 3600 } // Refresh every hour
)
```
**When to cache:**
- Data that changes less than once per hour
- Expensive aggregation queries
- Data shared across all users (not user-specific)
**When NOT to cache:**
- User-specific data that changes frequently
- Real-time data (use Supabase Realtime instead)
## 5. Select Only What You Need
```typescript
// Bad: Fetches all columns
const { data } = await supabase.from('users').select('*')
// Good: Fetches only needed columns
const { data } = await supabase.from('users').select('id, name, avatar_url')
```
-43
View File
@@ -1,43 +0,0 @@
# Error Tracking Setup (Sentry)
Track production errors automatically so you know about issues before your users report them.
## Setup (5 minutes)
### 1. Create Sentry Account
- Go to [sentry.io](https://sentry.io) (free tier available for small apps)
- Create a new project and select "Next.js"
### 2. Install Next.js Integration
```bash
npx @sentry/wizard@latest -i nextjs
```
This automatically:
- Installs `@sentry/nextjs`
- Creates `sentry.client.config.ts` and `sentry.server.config.ts`
- Updates `next.config.ts` with Sentry webpack plugin
### 3. Add Environment Variables
Add to `.env.local` (local) and Vercel Dashboard (production):
```bash
SENTRY_DSN=https://xxx@xxx.ingest.sentry.io/xxx
NEXT_PUBLIC_SENTRY_DSN=https://xxx@xxx.ingest.sentry.io/xxx
SENTRY_AUTH_TOKEN=sntrys_xxx # For source maps upload
```
### 4. Verify Setup
Trigger a test error and check Sentry Dashboard:
```typescript
// Temporary test - remove after verification
throw new Error("Sentry test error")
```
## What You Get
- Automatic error capture (client + server)
- Stack traces with source maps
- Error grouping and deduplication
- Email alerts for new errors
- Performance monitoring (optional)
## Alternative
**Vercel Error Tracking** - Built-in, simpler, but fewer features. Available in Vercel Dashboard under "Monitoring".
-67
View File
@@ -1,67 +0,0 @@
# Performance Monitoring
## Lighthouse Check (after every deployment)
1. Open Chrome DevTools (F12)
2. Go to Lighthouse tab
3. Select: Performance, Accessibility, Best Practices, SEO
4. Generate Report for both Mobile and Desktop
5. **Target: Score > 90** in all categories
## Common Performance Issues
### Unoptimized Images
```tsx
// Bad - unoptimized, no lazy loading
<img src="/large-image.jpg" />
// Good - Next.js Image component
import Image from 'next/image'
<Image src="/large-image.jpg" width={800} height={600} alt="Description" />
```
Next.js Image automatically: resizes, lazy-loads, serves WebP format.
### Large JavaScript Bundle
Use dynamic imports for heavy components that aren't needed on initial load:
```tsx
import dynamic from 'next/dynamic'
const HeavyChart = dynamic(() => import('./HeavyChart'), {
loading: () => <p>Loading chart...</p>,
})
```
### Missing Loading States
Always show feedback during data fetching:
```tsx
// Use shadcn Skeleton component
import { Skeleton } from "@/components/ui/skeleton"
if (isLoading) return <Skeleton className="h-12 w-full" />
```
### No Caching Strategy
Cache slow database queries with `unstable_cache`:
```typescript
import { unstable_cache } from 'next/cache'
export const getStats = unstable_cache(
async () => {
const { data } = await supabase.from('stats').select('*')
return data
},
['dashboard-stats'],
{ revalidate: 3600 } // Refresh every hour
)
```
## Quick Wins Checklist
- [ ] All images use `next/image` component
- [ ] Heavy components use dynamic imports
- [ ] Loading states show skeleton/spinner
- [ ] Fonts loaded with `next/font`
- [ ] No unnecessary client-side JavaScript (`"use client"` only when needed)
## Automated Monitoring
- **Vercel Analytics** - Automatic on Pro plan, shows Core Web Vitals
- **Vercel Speed Insights** - Real user performance data
-101
View File
@@ -1,101 +0,0 @@
# Rate Limiting
Prevent abuse, DDoS attacks, and excessive API usage.
## When to Add Rate Limiting
- **MVP:** Optional (focus on features first)
- **Production with users:** Recommended on auth endpoints and public APIs
- **Public-facing APIs:** Required
## Setup with Upstash Redis
### 1. Install Dependencies
```bash
npm install @upstash/ratelimit @upstash/redis
```
### 2. Create Upstash Account
- Go to [upstash.com](https://upstash.com) (free tier: 10k requests/day)
- Create a Redis database
- Copy REST URL and token
### 3. Add Environment Variables
```bash
# .env.local
UPSTASH_REDIS_REST_URL=https://xxx.upstash.io
UPSTASH_REDIS_REST_TOKEN=xxx
```
### 4. Create Rate Limiter
```typescript
// src/lib/rate-limit.ts
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
export const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
})
```
### 5. Use in API Routes
```typescript
// src/app/api/example/route.ts
import { ratelimit } from '@/lib/rate-limit'
import { NextRequest, NextResponse } from 'next/server'
export async function POST(request: NextRequest) {
const ip = request.headers.get('x-forwarded-for') ?? 'anonymous'
const { success, limit, remaining } = await ratelimit.limit(ip)
if (!success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: {
'X-RateLimit-Limit': limit.toString(),
'X-RateLimit-Remaining': remaining.toString(),
},
}
)
}
// Process request normally...
}
```
### 6. Use in Middleware (Global)
```typescript
// middleware.ts
import { ratelimit } from '@/lib/rate-limit'
import { NextRequest, NextResponse } from 'next/server'
export async function middleware(request: NextRequest) {
// Only rate limit API routes
if (request.nextUrl.pathname.startsWith('/api/')) {
const ip = request.headers.get('x-forwarded-for') ?? 'anonymous'
const { success } = await ratelimit.limit(ip)
if (!success) {
return NextResponse.json({ error: 'Too Many Requests' }, { status: 429 })
}
}
}
export const config = {
matcher: '/api/:path*',
}
```
## Recommended Limits
| Endpoint Type | Limit | Window |
|--------------|-------|--------|
| Login/Register | 5 requests | 1 minute |
| Password Reset | 3 requests | 5 minutes |
| General API | 30 requests | 10 seconds |
| File Upload | 5 requests | 1 minute |
## Alternative
**Vercel Edge Config** - Simpler but less flexible. Built into Vercel, no external service needed.
-64
View File
@@ -1,64 +0,0 @@
# Security Headers Configuration
Protect against XSS, Clickjacking, MIME sniffing, and other common web attacks.
## Setup
Add security headers to `next.config.ts`:
```typescript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin',
},
{
key: 'Strict-Transport-Security',
value: 'max-age=31536000; includeSubDomains',
},
],
},
]
},
}
export default nextConfig
```
## What Each Header Does
| Header | Protection |
|--------|-----------|
| X-Frame-Options: DENY | Prevents your site from being embedded in iframes (clickjacking) |
| X-Content-Type-Options: nosniff | Prevents browsers from guessing content types (MIME sniffing) |
| Referrer-Policy | Controls how much URL info is sent to other sites |
| Strict-Transport-Security | Forces HTTPS connections |
## Verify After Deployment
1. Open Chrome DevTools
2. Go to Network tab
3. Click on any request to your site
4. Check Response Headers section
5. Verify all 4 headers are present
## Advanced (Optional)
**Content-Security-Policy (CSP)** - The most powerful header, but can break your app if misconfigured. Only add after thorough testing:
```
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
```
Start with report-only mode first: `Content-Security-Policy-Report-Only`