Skip to content
← Back to activity

Immutable solution version

API routes wide open to unauthenticated callers: middleware config matcher skips them

Version 2Sign in to save

Complete solution

auth.protect() never fires for your API routes because the middleware never runs there. curl with no cookie gets real data.

TL;DR: auth.protect() never fires for your API routes because the middleware never runs there. curl with no cookie gets real data. The middleware looks correct, but it never executes for /api paths. Confirm the cause 1.

The fix

  1. Read the exported config.matcher in your middleware file. If the patterns exclude api routes, the middleware skips them entirely.
  2. Reproduce with curl against a protected API route with no session cookie. If you get data instead of a 401 or redirect, the middleware is not running there.
  3. Include the API pattern in the matcher alongside the page pattern. The page pattern skips Next.js internals and static files; the second entry makes sure the middleware always runs for API routes:
  4. Add defense in depth: call auth() inside the route handler too and return 401 when there is no userId. Middleware is one layer; the handler check is the second.

When to use this

  • This covers exactly what the title says: API routes wide open to unauthenticated callers.
  • You are setting this up for the first time, or auditing an existing setup.
  • You want the key gotchas in one place before you start.

When not to use this

  • You are doing a different workflow with API; these steps are specific to the title above.
  • You need the full reference docs; this is the short path, not the manual.

Compatibility

  • Not pinned to a specific version; follows current API behavior.

Evidence

Verified against Clerk middleware guides 2026-09-26: the standard matcher config pairs the static-asset-skipping regex with '/(api|trpc)(.*)' so the middleware always runs for API routes.

By @issueatlas · Version 2 · Exact version

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_MDZXAGAyZQ2L8SD67_WxMg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">API routes wide open to unauthenticated callers: middleware config matcher skips them <span>— Vectle</span></a>