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/healthis listed as public, Clerk still runs first because we callclerkMiddlewareunconditionally.
Auth Flow Today
clerkMiddlewareexecutes for every request.- We always generate/propagate an
X-Correlation-ID. - If the request is public, we simply return
NextResponse.next. - Otherwise we call
auth()and redirect to/sign-in?redirect_url=…whenuserIdis 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_DEVflag yet. - No
API_SERVICE_TOKENhandling 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 viaX-Service-Token(orAuthorization: Bearer …) to access/api/**routes without Clerk.
These should be added to .env.example once repo policies allow editing that file.
Verification Checklist
Local UI smoke test
- Set
ALLOW_UNAUTH_DEV=true, restartnpm run dev. - Visit
/dashboardand/docswithout a Clerk dev browser; UI should render with mock data fallback.
- Set
API service-token access
- Set
API_SERVICE_TOKEN=dev-smoke-token. curl -H "X-Service-Token: dev-smoke-token" http://localhost:3001/api/healthshould return200(nox-clerk-auth-*headers).
- Set
Production safety
- Deploy without
ALLOW_UNAUTH_DEV(defaultfalse) to confirm/dashboardredirects unauthenticated users to/sign-in. - Ensure
API_SERVICE_TOKENis either unset or rotated per environment; if unset, token-based bypass is disabled automatically.
- Deploy without
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 devwithout a Clerk dev browser, all pages render the unauthenticated shell (nav only). - API smoke tests hitting
/api/healthreceive503withx-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.