Fixing Auth Bypass Risks in Next.js Middleware
Relying exclusively on middleware.ts as a perimeter wall leaves your routes exposed whenever a matcher regex misses a path or a framework bug bypasses middleware execution (like CVE-2025-29927 in older Next.js builds).
AI tools love generating a single `middleware.ts` file that redirects unauthenticated users away from `/dashboard`, and then leaving every `/api/*` route and Server Action completely unauthenticated underneath.
- Forgotten matcher rules leave new `/api/admin/*` routes completely open
- Outdated Next.js versions prior to patched 15.2.3+ were vulnerable to x-middleware-subrequest bypass
- API routes and Server Actions can be hit directly even when UI pages redirect
Vulnerable Pattern vs. Production Fix
// app/api/admin/export/route.ts — VULNERABLE!
export async function GET() {
// Relies solely on middleware.ts matching /api/admin — ZERO check here!
const leads = await db.waitlist.findMany();
return Response.json(leads);
}// lib/dal.ts — Centralized Data Access Layer
import "server-only";
import { cache } from "react";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const requireAdmin = cache(async () => {
const supabase = await createServerSupabaseClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user || user.app_metadata?.role !== "admin") {
throw new Error("FORBIDDEN");
}
return user;
});
// app/api/admin/export/route.ts
export async function GET() {
try {
await requireAdmin();
const leads = await db.waitlist.findMany();
return Response.json(leads);
} catch {
return Response.json({ error: "Forbidden" }, { status: 403 });
}
}Copy-Paste AI Fix Prompt (Cursor · Lovable · Bolt · Claude Code)
Eliminate middleware-only authentication assumptions in this Next.js app: 1. Verify package.json uses a patched Next.js version (15.3.3+ or latest patched release). 2. Create a server-only Data Access Layer (lib/dal.ts) with requireSession() and requireAdmin() helpers. 3. Ensure EVERY protected Server Component, Server Action, and app/api/**/route.ts handler calls requireSession() (or requireAdmin()) directly instead of relying on middleware.ts alone. 4. Keep middleware.ts strictly for fast UX redirects and session cookie refresh.
How to Verify Your Fix Worked
- 1Confirm Next.js version in package.json is >= 15.2.3 (e.g. 15.3.3).
- 2Temporarily comment out middleware.ts locally and hit protected API routes with curl — every single one should still return 401/403!
- 3Restore middleware.ts and re-verify normal login UX.
Frequently Asked Questions
Should I still use middleware.ts in Next.js?
Yes — middleware is great for optimistic UX redirects and refreshing Supabase/Auth session cookies, as long as your actual data access and API routes independently verify auth.
Why should I check app_metadata instead of user_metadata for admin roles in Supabase?
Users can modify their own `user_metadata` via supabase.auth.updateUser()! Always store roles/permissions in `app_metadata` or a protected server-managed roles table.
How does `requireSession` affect performance?
Wrapping it in React's `cache()` deduplicates auth lookups within a single server render pass so it runs at most once per request.