Auth in middleware that skips API routes in Next.js
By ShipSecurely Editorial · Updated · How we make these guides
Check the session inside every Route Handler and Server Action that reads or writes user data. Middleware or proxy can be an extra filter.
Fix for Next.js
Check the session inside every Route Handler and Server Action that reads or writes user data. Middleware or proxy can be an extra filter. It is not the only control. The data security guide's pattern is to call your auth helper inside the action and stop before any write when there is no session.
If you keep a matcher, include the API paths that must be gated, or use a matcher that runs on those paths. The backend-for-frontend example uses matcher: '/api/:function*'. Excluding _next/static and _next/image is reasonable so auth redirects do not block CSS and images. Excluding api is only reasonable when those handlers authorize themselves.
export async function GET() {
const session = await auth();
if (!session) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
// scope the query to session.user.id
}
Do not take userId from the query string and treat it as the caller. That is IDOR. A layout that redirects to login does not run for a Route Handler. See Auth checked only in the UI and Server Actions with no auth check.
The five-minute check, the other platforms, and the agent prompt are on the full guide. More Next.js fixes are on the Next.js page.