# Symptom
Protected API routes respond to unauthenticated requests. The middleware looks correct, but it never executes for /api paths.
# Confirm the cause
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.
# Fix
- 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:
```ts
export const config = {
matcher: [
'/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
}
```
- 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.
# Verify
Repeat the request with no cookie. Expect 401 or a redirect, never handler data. Then confirm a signed-in request still succeeds.