Menu

Middleware is not your auth layer (a Next.js footgun I keep finding)
📰

Middleware is not your auth layer (a Next.js footgun I keep finding)

DEV Community: nextjs·Somnath Khadanga·18 days ago
#2c27hzkw
#devtonextjs#devto#dev#users#user
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.