Description
Current State
Every API route repeats the same 15-20 lines of boilerplate:
// This pattern appears in 99 API routes
const supabase = createApiSupabaseClient(request)
if (!supabase) {
return NextResponse.json({ error: 'Database connection failed' }, { status: 500 })
}
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { data: userProfile } = await supabase
.from('user_profiles')
.select(`id, email, name, is_superadmin, user_roles(...)`)
.eq('id', (user as any).id) // Note the 'as any'
.single()
if (!userProfile) {
return NextResponse.json({ error: 'User profile not found' }, { status: 404 })
}
Desired Outcome
Create a composable middleware system:
// lib/api/middleware.ts
export function withAuth<T>(
handler: (req: NextRequest, ctx: AuthContext) => Promise<NextResponse>
) {
return async (req: NextRequest) => {
const authResult = await getAuthenticatedUser(req);
if (authResult.error) return authResult.error;
return handler(req, authResult.context);
};
}
// Usage in route
export const POST = withAuth(async (req, { supabase, user, userProfile }) => {
// Route logic with guaranteed auth context
});
Implementation approach
- Create
lib/api/middleware.ts with auth wrapper
- Create
lib/api/error-response.ts for consistent error formats
- Migrate 5-10 routes as proof of concept
- Document pattern for other contributors
Files to reference
lib/server-guards.ts - Has some guard functions already
lib/auth-guards.ts - Permission checking guards
Acceptance Criteria
Description
Current State
Every API route repeats the same 15-20 lines of boilerplate:
Desired Outcome
Create a composable middleware system:
Implementation approach
lib/api/middleware.tswith auth wrapperlib/api/error-response.tsfor consistent error formatsFiles to reference
lib/server-guards.ts- Has some guard functions alreadylib/auth-guards.ts- Permission checking guardsAcceptance Criteria
lib/api/middleware.tswithwithAuthwrapperlib/api/error-response.tswith helper functionsdocs/api/MIDDLEWARE.md