Documentation

Guides and references

Backend

Middleware

middleware.ts flow, CORS, rate limiting, Supabase session.

Overview

middleware.ts runs on every request (except static assets). It handles:

  1. CORS for API routes
  2. Rate limiting on auth endpoints
  3. Supabase session refresh
  4. 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.tsupdateSession():

  • 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/image
  • favicon.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.