AleannLab

Next.js Middleware That Skips Your API Routes: Check the Matcher

AleannLab team3 min read

Next.js middleware runs only for the paths its matcher covers. If the matcher lists /dashboard/:path* and your data comes from /api/*, the pages are protected and the data is not. Test by calling an API route directly without a session. Then put the real auth check inside each route handler and server action, and treat middleware as a convenience for redirects.

On this page
  1. The gap
  2. More ways middleware misses requests
  3. Test it in two minutes
  4. Where the check belongs
  5. What middleware is still good for

Middleware feels like the perfect place for auth: one file, runs before everything. AI assistants like it for the same reason. The trouble is the word "everything".

The gap

A typical generated setup:

TypeScript
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  const session = req.cookies.get('session');
  if (!session) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/settings/:path*'],
};

Visit /dashboard logged out and you are redirected. It looks done.

The dashboard loads its data from /api/orders. That path is not in the matcher, so the middleware never runs for it:

bash
curl https://yourapp.com/api/orders
# 200, with everyone's orders

The other popular matcher has the same hole, written the other way round:

TypeScript
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],

This one says "run on everything except /api". It comes from documentation examples where API routes handle their own auth. Copied into a project where they do not, it documents the vulnerability in the config.

More ways middleware misses requests

  • New routes. Someone adds /reports or /api/export and forgets the matcher. Nothing fails. The route is simply open.
  • Server Actions. An action is a POST to the page it is used on. An action imported into a public page is reachable through that public path. See our post on Server Actions without an auth check.
  • Presence checks. The example above only checks that a cookie exists. Any value passes: curl -H "Cookie: session=x". Middleware has to verify the session, not notice it.
  • Framework bugs. In March 2025, CVE-2025-29927 allowed attackers to skip Next.js middleware entirely by sending an x-middleware-subrequest header. Apps whose only auth check lived in middleware were fully exposed until they upgraded. Apps that also checked in their handlers were not.

That last one is the argument for layers. You cannot predict the next bypass. You can make sure a bypass of one layer is not enough.

One naming note: Next.js 16 renamed the file from middleware.ts to proxy.ts. The matcher works the same way, and so does everything in this post.

Test it in two minutes

  1. Log in, open the network tab, and collect the API calls your pages make.
  2. Replay each with no cookies:
bash
curl -i https://yourapp.com/api/orders
curl -i -X POST https://yourapp.com/api/orders -d '{}' -H 'Content-Type: application/json'
  1. Replay with a junk cookie: -H "Cookie: session=anything".

Protected routes should answer 401. A 200, or a 500 from deep inside your business logic, means the request got further than it should.

Where the check belongs

In the code that touches the data:

TypeScript
// app/api/orders/route.ts
import { auth } from '@/lib/auth';

export async function GET() {
  const session = await auth();
  if (!session) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const orders = await db.order.findMany({
    where: { userId: session.user.id },
  });
  return Response.json(orders);
}

Two things happen here that middleware cannot do well. The session is verified against the server's record. And the query is scoped to the caller with where: { userId: session.user.id }. Middleware can answer "is someone logged in?". It cannot answer "is this their order?". That second question is what our post on IDOR is about.

A structure that scales: put data access in one module (a "data access layer"), and make every function in it take the session and enforce ownership. Route handlers, server components and actions all go through it. There is one place to review.

What middleware is still good for

  • Redirecting logged-out visitors to /login before a page renders.
  • Refreshing session cookies.
  • Locale and A/B routing, security headers.

If you keep an auth redirect there, match broadly and let handlers deal with their own responses:

TypeScript
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|login|signup).*)'],
};

With this matcher /api is covered too. For API paths, return a 401 JSON response instead of a redirect.

This is check 1 in our security checklist for vibe-coded apps. If you would like every route in your app replayed without a session and fixed where it answers, that is part of our app rescue and security audit.

All articles →

Ready to discuss your project with us?

idea
*
*
*
I'm interested in...
Web Development
App Development
UX/UI Design
DevOps
Artificial Intelligence And Machine Learning
QA Testing
Mobile Development
Consultation
OutSource
Project budget (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Upload file