All posts
nextjssecurity

Middleware Is Not Your Auth Layer

In March, one request header was enough to skip Next.js middleware entirely. The patch took minutes. The lesson took longer, because the real bug was where I had put the check.

Muhamad Choirul Adam 3 min readPhoto: Unsplash

In late March, Next.js disclosed CVE-2025-29927. Next.js uses an internal header, x-middleware-subrequest, to stop middleware from calling itself in a loop. On self-hosted apps, a client could send that header itself, and the framework would treat the request as one that had already run middleware and skip it.

If your middleware was the thing that redirected logged-out users away from /admin, that redirect simply didn't happen.

The patch was the easy part

The fix shipped in 15.2.3, 14.2.25, 13.5.9, and 12.3.5. Updating took one command. Apps on Vercel weren't affected, and anything behind a proxy could strip the header as a stopgap.

The more useful question was the one I asked after updating: if middleware had been skipped on my apps, what would an attacker have reached?

Where the check lived

For a couple of dashboards, the honest answer was "more than I'd like." Middleware checked for a session cookie and redirected. The pages and route handlers behind it assumed that if they were running, someone had already checked.

Rendering diagram…

That's one gate in front of everything, and nothing behind it. Any bug in the gate opens the whole building.

What I moved, and where

Middleware is good at cheap, early decisions: redirects, rewrites, locale, an optimistic "you're probably not logged in" bounce. It's a bad place to be the only check, because it runs separately from the code that actually reads data.

So the rule I follow now: every place that reads or writes data checks access itself.

lib/auth.ts
import "server-only";
 
export async function requireUser(role?: Role) {
  const session = await getSession();
  if (!session) redirect("/login");
  if (role && !session.user.roles.includes(role)) forbidden();
  return session.user;
}
app/admin/orders/page.tsx
export default async function OrdersPage() {
  const user = await requireUser("admin");
  const orders = await getOrders({ tenantId: user.tenantId });
  return <OrdersTable orders={orders} />;
}

The same call goes at the top of every server action and route handler. It's repetitive on purpose. When I review a new endpoint, the first line tells me who can call it.

LayerJob after the change
MiddlewareFast redirects, nicer UX. Not trusted for access.
Page / action / handlerThe real check, right next to the data it protects
Data access functionScopes every query to the user's tenant or ownership

Why it matters

This wasn't really a Next.js lesson. Any app with one gate in front of everything has the same shape, whether the gate is middleware, an API gateway, or a reverse proxy rule. Gates fail. The fix is to make sure the thing behind the gate doesn't assume it worked.