When I audit Next.js apps built quickly (often with AI tools), one pattern shows up more than any other: routes are protected in middleware.ts , and the API route handlers trust that.
// app/api/admin/users/route.ts export async function GET ( request : NextRequest ) { // "middleware already checked" const users = await db . user . findMany () return NextResponse . json ( users ) }
Enter fullscreen mode
Exit fullscreen mode
Middleware can be skipped by a matcher that doesn't cover a new route, misconfigured during a refactor, or bypassed by calling the API directly. If the handler doesn't check, the data is open.
The fix is boring: every handler that touches user data verifies the session and role itself.
export async function GET ( request : NextRequest ) { const session = await getServerSession ( authOptions ) if ( ! session ) return NextResponse . json ({ error : ' Unauthorized ' }, { status : 401 }) if ( session . user . role !== ' admin ' ) return NextResponse .…