* docs: regenerate API documentation from src/app/api (329 routes) The generator only recognised `export async function GET`, so every route exported as a guarded const (`export const GET = withAdmin(...)`) or a destructured re-export was missing: the doc listed 116 endpoints, many of them since renamed or removed, against 329 route files today. Teach it the other two export shapes and the withAuth/withAdmin guards, and regenerate both copies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD * docs: archive dated audits, compliance trackers and migration proposals Moves point-in-time records into docs/archive/ (with a README saying they describe the day they were written): the 2026-01 dev-guide compliance plan, codebase audit, DRY/SSOT and Phase 1 fix logs, the 2026-02 overnight cross-project plan, the 2026-07-02 audit report, the 2026-07-06 Shopware migration plan and system migration strategy, and CODE_AUDIT.md. CODE_AUDIT.md was listed in .claude/CLAUDE.md, .gemini/GEMINI.md and docs/README.md as the current list of issues to fix while its own banner called it a historical snapshot; those entries now point at docs/AUDIT_BACKLOG_2026-08.md, the list of findings still open. docs/README also stops linking api/, legacy/ and reference/, which do not exist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD * docs: archive closed trackers and docs for removed code Into docs/archive/: ARCHITECTURE_DEBT (status CLOSED 2026-06-30), DATABASE_AUDIT (Neon, pre-cutover), UPGRADE_PLAN (2026-06-03 snapshot; Tailwind 4 and React 19 are done), MIGRATION_PLAN_QQQ5 and PROFILES_SSOT_PLAN (both executed: migrations 105 and 121/122), production-ready-checklist (Frauenfeld plan that never shipped), and three docs whose code is gone: PROJECT_PAGES_GUIDE (src/components/projects and the per-project pages, now one [slug] route), RevampCopilot (no src/features/chatbot) and projects/upcycling (the /projects/upcycling pages and businessPlan messages are no longer in the tree). Inbound references follow the move, including three code comments. SHARED_CONTEXT and COMMANDS stop describing the upcycling mini-site as live; COMMANDS drops db:migrate-users, which is not a script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD * docs: correct live docs against the tree - BLOG_SYSTEM: rewritten from the code. There is no TinaCMS and no content/submissions; posts merge content/posts/*.md with blog_posts, and submissions are blog_submissions rows reviewed by staff. - installation guide: rewritten. There is no cms-api, no docker-compose.dev.yml and no default admin password; setup is services:up, db:migrate, setup-admins, dev. - RELIABILITY: migration 005b (not 005), no ENABLE_CMS gate, prod facts. - RESPONSIVE_DESIGN_SYSTEM: ResponsiveSection/Hero/Heading were removed; document Section, PageHero and Heading instead. - DEAD_CODE: the /api/repairers and /api/it-hilfe/helpers proxies and the routes.helpers alias are deleted, not 410; fix a stale line range. - DEV_GUIDE, AGENTS, claude/cursor/gemini guides, .cursorrules: DEVELOPMENT_GUIDELINES.md never existed here; protected files are in .claude/CLAUDE.md. src/config/site.ts -> org.ts/urls.ts; Next.js 16. - src/middleware.ts -> src/proxy.ts; components/ui/Button.tsx -> src/components/ui/button.tsx; reference page paths. - docs-paths baseline 68 -> 6, as the check asks when the count falls. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD * docs: fix dead links in package and example READMEs ai-native-cms-core linked a Next.js plugin, a CLI and docs/quick-start.md that do not exist in this repo; ai-native-cms-react has no README; the saldo README pointed at the repo root instead of the implementation in src/lib/team/saldo.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD --------- Co-authored-by: Claude <noreply@anthropic.com>
9.9 KiB
Database & Backend Architecture - RevampIT
Created: 2026-01-05
Last Modified: 2026-06-19
Last Modified Summary: Updated production deployment section — self-hosted Postgres 17 on Hetzner, single shared DATABASE_URL pool, R2 backups
Overview
RevampIT uses a PostgreSQL-based unified backend with Next.js API routes serving as the backend layer. The architecture follows a serverless-first approach where API routes handle all backend logic, connecting directly to PostgreSQL databases.
🗄️ Database Architecture
Database Setup
The project uses PostgreSQL as its primary database:
- Main Database (
revampit_db- Port 5433)- User authentication & profiles
- Workshops & registrations
- Service appointments
- Inventory & marketplace listings
- E-commerce products & orders
- Messaging system
- Blog & content
Database Connection
Connection Pool Pattern:
// src/lib/auth/db.ts
- Uses PostgreSQL connection pooling (max 20 connections)
- Singleton pattern for pool management
- Automatic connection retry and error handling
- Graceful degradation when DB is unavailable
Configuration:
- Host:
localhost(orDB_HOSTenv var) - Port:
5433 - Pool Size: 20 concurrent connections
- Timeout: 5 seconds connection timeout
- Idle Timeout: 30 seconds
🔌 Backend Architecture
Next.js API Routes (Serverless Backend)
The backend is entirely built using Next.js API Routes - no separate backend server:
src/app/api/
├── auth/ # Authentication endpoints
│ ├── register/ # POST /api/auth/register
│ ├── login-status/ # POST /api/auth/login-status
│ └── verify-email/ # GET /api/auth/verify-email
├── workshops/ # Workshop management
│ └── route.ts # GET /api/workshops
├── appointments/ # Service appointments
├── shop/ # E-commerce
└── user/ # User profile management
Request Flow
User Request
↓
Next.js Middleware (src/middleware.ts)
↓
API Route Handler (src/app/api/*/route.ts)
↓
Database Query Functions (src/lib/auth/db.ts)
↓
PostgreSQL Database
↓
Response to User
Example: User Registration Flow
// 1. User submits form → POST /api/auth/register
// src/app/api/auth/register/route.ts
export async function POST(request: Request) {
// 2. Parse request body
const { email, password, name } = await request.json()
// 3. Call registration function
const result = await registerUser({ email, password, name })
// 4. Return response
return apiSuccess({ message: 'Konto erstellt', user: result.user })
}
// 5. registerUser() calls database functions
// src/lib/auth/db.ts → createUser()
// 6. Database query executes
// 7. User record created in PostgreSQL
🔐 Authentication System
Auth.js v5 (NextAuth)
Session Strategy: JWT (JSON Web Tokens stored in cookies)
How it works:
- User logs in → Credentials validated against
userstable - Session token created → Stored in HTTP-only cookie
- Middleware checks cookie → Protects routes
- API routes verify session →
await auth()from@/auth
Database Tables:
users- User accountssessions- Active sessions (if using database strategy)verification_tokens- Email verification & password reset tokensuser_profiles- Extended user profile data
Password Security:
- Hashing: bcrypt with 12 salt rounds (OWASP recommended)
- Validation: 12+ characters, uppercase, lowercase, numbers, special chars
- Storage: Never stored in plain text, only
password_hashin database
📊 Database Schema Overview
Core Tables
Users & Authentication:
users
├── id (UUID)
├── email (unique)
├── password_hash (bcrypt)
├── name
├── role (user, admin, seller, repairer)
├── email_verified
user_profiles
├── user_id (FK → users)
├── first_name, last_name
├── address, city, canton, postal_code
├── phone, mobile
└── preferences (JSON)
Workshops:
workshops
├── id, slug, title
├── category, level, duration
└── price_cents
workshop_instances
├── id, workshop_id (FK)
├── start_date, location
└── max_participants
workshop_registrations
├── id, user_id (FK), instance_id (FK)
├── status, payment_status
└── payment_amount_cents
Services:
service_types
├── id, slug, name
├── duration_minutes, price_cents
└── requires_approval
service_appointments
├── id, user_id (FK), service_type_id (FK)
├── preferred_date, confirmed_date
├── status, urgency
└── price_charged_cents
Inventory & Marketplace:
inventory_items
├── id, kivitendo_article_number
├── quantity_available, selling_price_chf
ai_extracted_products
├── id, inventory_item_id (FK)
├── product_name, brand, category
└── sustainability_scores (JSON)
marketplace_listings
├── id, user_id (FK)
├── product_data (JSON)
└── status (draft, published, sold)
🔄 Database Query Pattern
Standard Query Function
// src/lib/auth/db.ts
export async function query<T = unknown>(
text: string,
params?: QueryParams
): Promise<{ rows: T[]; rowCount: number }> {
const pool = getPool()
const result = await pool.query(text, params)
return {
rows: result.rows as T[],
rowCount: result.rowCount || 0
}
}
Example Usage
// Get user by email
const user = await getUserByEmail('user@example.com')
// Create workshop registration
await query(
'INSERT INTO workshop_registrations (user_id, instance_id, status) VALUES ($1, $2, $3)',
[userId, instanceId, 'confirmed']
)
// Get user's workshops
const workshops = await getUserWorkshopRegistrations(userId)
Error Handling
// Graceful degradation on connection errors
try {
const result = await query('SELECT * FROM users')
} catch (error) {
if (error.message.includes('connect')) {
// Return user-friendly error instead of crashing
return { error: 'Database temporarily unavailable' }
}
throw error
}
🔒 Security Features
Database Security
- Parameterized Queries: All queries use
$1, $2placeholders (prevents SQL injection) - Connection Pooling: Limits concurrent connections
- Error Handling: Doesn't expose database errors to users
- Password Hashing: bcrypt with 12 rounds
API Security
- Session Validation: All protected routes check
await auth() - Rate Limiting: Built into Auth.js (configurable)
- CORS: Configured per route
- Input Validation: All inputs validated before database queries
📡 API Response Pattern
Standardized Responses
// src/lib/api/helpers.ts
// Success response
apiSuccess({ data: {...}, message: 'Success' })
// → { success: true, data: {...}, message: 'Success' }
// Error response
apiError(error, 'User-friendly message', 500)
// → { success: false, error: 'User-friendly message' }
// Bad request
apiBadRequest('Validation failed', ['field1', 'field2'])
// → { success: false, error: 'Validation failed', errors: [...] }
🚀 Deployment Architecture
Local Development
Docker Compose
├── PostgreSQL (port 5433) - Main DB
├── Redis (port 6380) - Cache
└── Meilisearch (port 7700) - Product search
Next.js Dev Server (port 3000)
└── API Routes → Database connections
Production (self-hosted Hetzner box)
Production is not serverless. The app and its database run on a single
self-hosted Hetzner server (evig.orangecat.ch, ssh ubuntu@167.233.22.31),
deployed via GitHub Actions → build → rsync → systemd (no Vercel).
Next.js standalone server (systemd service on the Hetzner box)
├── All API routes served by one long-lived Node process
└── Connects to the local Postgres over DATABASE_URL
Database (Production)
├── Self-hosted Postgres 17 on the SAME box
│ DATABASE_URL=postgresql://…@localhost:5432/revampit
├── getDbConfig() uses DATABASE_URL → ONE pool shared by app + auth
└── Nightly off-box backup to Cloudflare R2 (`revampit-backups`)
via systemd `evig-backup.timer`
(see scripts/ops/README.md and docs/DISASTER_RECOVERY.md)
🔍 Monitoring & Health Checks
Health Check Endpoints
// src/app/api/health/auth-db/route.ts
GET /api/health/auth-db
// Checks database connectivity and returns diagnostics
Logging
// src/lib/logger.ts
logger.info('User registered', { userId, email })
logger.error('Database error', { error, query })
📝 Key Files Reference
| File | Purpose |
|---|---|
src/lib/auth/db.ts |
Database connection pool & query functions |
src/config/database.ts |
Database configuration & table names |
src/auth.ts |
Auth.js configuration & session management |
src/app/api/**/route.ts |
API route handlers (backend endpoints) |
src/proxy.ts |
Route protection & session validation (Next.js 16 proxy, formerly middleware.ts) |
docker-compose.yml |
Local database setup |
scripts/db/migrations/*.sql |
Database schema migrations |
🎯 Summary
Backend = Next.js API Routes (no separate server)
- Each
/api/*route is a serverless function - Connects directly to PostgreSQL via connection pool
- Handles authentication, business logic, and data access
Database = PostgreSQL
- Main DB: Users, workshops, services, content, e-commerce products & orders
Architecture Benefits:
- ✅ Serverless (scales automatically)
- ✅ Type-safe (TypeScript throughout)
- ✅ Secure (parameterized queries, session validation)
- ✅ Maintainable (centralized database functions)
- ✅ Fast (connection pooling, optimized queries)