Most authorization bugs happen in the gaps
An application rarely fails because an engineer forgot to write an if (!session) check on the primary dashboard. It fails when a new export route, bulk action, or background endpoint ships without the same guard—or when a route checks authentication (401) without verifying tenant ownership (403 / 404).
Fail-closed design means an unannotated or misconfigured handler rejects traffic by default rather than falling back to public access.
Declare every entry point explicitly
In a growing Next.js App Router codebase, route handlers live across dozens of directories. Maintaining an explicit entry-point registry—mapping each route to its required authentication mode, capability, and rate-limit policy—turns security review into a deterministic check rather than a grep exercise.
export const routePolicy = {
'GET /api/admin/orders': { auth: 'staff', capability: 'orders.read' },
'POST /api/admin/orders/export': { auth: 'staff', capability: 'orders.export' },
'POST /api/contact': { auth: 'public', rateLimit: 'contact' },
} as const;A unit test can then walk src/app/api/**/route.ts and fail the build if any route file is missing from the policy table.
Separate authentication, authorization, and resource scope
Every protected handler should resolve three questions in order:
- Who is calling? Verify the session token or signed credential on the server. Never trust client-supplied
userIdorrolefields. - Are they allowed to perform this action? Check a granular capability (for example,
careers.manage) rather than scattering role string comparisons across components. - Does this record belong to their scope? Include
workspaceIdoruserIddirectly in the databaseWHEREclause.
Returning 404 when a record exists outside the caller's scope avoids confirming whether an ID belongs to another user.
Validate and bound every payload
Pair RBAC with strict input boundaries:
- Parse JSON bodies with an explicit size cap before validation so oversized payloads fail fast.
- Use strict schema validation (rejecting unknown keys on sensitive mutations) so mass-assignment fields like
roleorstatuscannot slip through. - Enforce same-origin checks on cookie-authenticated
POST,PATCH, andDELETEhandlers.
Verify the negative cases
A contract is only real when tests prove what it blocks. For every critical mutation, test an unauthenticated caller (401), an authenticated caller missing the capability (403), a cross-tenant ID (404), and a cross-origin request (403).