Middleware & Env State (Nov 2025)

This document captures the current behavior of apps/scorm-api/middleware.ts before we add a dev bypass + service-token support.

Public Route Matchers

const isPublicApiRoute = createRouteMatcher([
  '/api/health(.*)',
  '/api/v1(.*)',
  '/api/docs(.*)',
  '/api/webhooks/stripe(.*)',
]);

const isPublicAppRoute = createRouteMatcher([
  '/',
  '/docs(.*)',
  '/sign-in(.*)',
  '/sign-up(.*)',
  '/help(.*)',
  '/onboarding/(.*)',
]);
  • Any route NOT captured above runs through Clerk.
  • Even though /api/health is listed as public, Clerk still runs first because we call clerkMiddleware unconditionally.

Auth Flow Today

  1. clerkMiddleware executes for every request.
  2. We always generate/propagate an X-Correlation-ID.
  3. If the request is public, we simply return NextResponse.next.
  4. Otherwise we call auth() and redirect to /sign-in?redirect_url=… when userId is missing.

There is no environment check or bypass flag—dev instances require a Clerk dev-browser cookie just like production.

Environment Variables

  • SKIP_MIDDLEWARE_AUTH, SKIP_LAYOUT_AUTH (historical flags) are not referenced in middleware anymore.
  • No ALLOW_UNAUTH_DEV flag yet.
  • No API_SERVICE_TOKEN handling in the middleware; API smoke tests must present a Clerk session.

Upcoming Env Variables

  • ALLOW_UNAUTH_DEV — enable only in local development to bypass Clerk middleware entirely.
  • API_SERVICE_TOKEN — shared secret that automated clients can send via X-Service-Token (or Authorization: Bearer …) to access /api/** routes without Clerk.

These should be added to .env.example once repo policies allow editing that file.

Verification Checklist

  1. Local UI smoke test

    • Set ALLOW_UNAUTH_DEV=true, restart npm run dev.
    • Visit /dashboard and /docs without a Clerk dev browser; UI should render with mock data fallback.
  2. API service-token access

    • Set API_SERVICE_TOKEN=dev-smoke-token.
    • curl -H "X-Service-Token: dev-smoke-token" http://localhost:3001/api/health should return 200 (no x-clerk-auth-* headers).
  3. Production safety

    • Deploy without ALLOW_UNAUTH_DEV (default false) to confirm /dashboard redirects unauthenticated users to /sign-in.
    • Ensure API_SERVICE_TOKEN is either unset or rotated per environment; if unset, token-based bypass is disabled automatically.

Share this document (and README updates) with the team whenever flags change so QA knows which mode to expect.

Observed Impact

  • When running npx next dev without a Clerk dev browser, all pages render the unauthenticated shell (nav only).
  • API smoke tests hitting /api/health receive 503 with x-clerk-auth-reason: dev-browser-missing.

These notes will be used to verify that the upcoming changes (dev bypass + service-token support) cover every scenario.