Backend
Middleware
middleware.ts flow, CORS, rate limiting, Supabase session.
Overview
middleware.ts runs on every request (except static assets). It handles:
- CORS for API routes
- Rate limiting on auth endpoints
- Supabase session refresh
- Protected route redirects
Flow
Request → CORS (if /api/*) → Rate limit (auth endpoints) → updateSession → Response
CORS
lib/middleware/cors.ts:
- Handles preflight OPTIONS for API routes
- Adds CORS headers to API responses via
addCorsHeaders - Configure allowed origins in env or config
Rate Limiting
lib/middleware/rate-limit.ts:
- IP-based rate limiting on auth endpoints:
/api/auth/magic-link/api/auth/login/api/auth/signup/api/auth/forgot-password/api/auth/reset-password/api/auth/change-password
- Upstash Redis when
UPSTASH_REDIS_REST_*env vars are set; otherwise in-memory fallback - Prevents brute force and abuse
Supabase Session
lib/supabase/middleware.ts — updateSession():
- Refreshes Supabase session from cookies
- Redirects unauthenticated users from protected routes (e.g.
/dashboard/*) - Soft-gates incomplete onboarding (
profiles.onboarding_completed) to/onboarding - Redirects authenticated users from auth pages (e.g.
/login) to dashboard when appropriate
Matcher
The middleware matcher excludes:
_next/static_next/imagefavicon.ico- Image files (svg, png, jpg, etc.)
Extending
To add rate limiting to more routes, extend the pathname.startsWith checks in middleware.ts. To add new protected paths, update updateSession or the Supabase middleware config.