Authentication
Secure Auth Flow
Production-ready authentication with server-side session checks and route protection.
Problem this solves
Teams often ship auth quickly but leave gaps around role checks, token leakage, and route guards.
When to use it
- You need multi-role authentication in a Next.js app.
- You want to enforce protected routes on the server, not only in the client.
- You need secure API access with reusable auth helpers.
Code snippet
typescript
// app/api/projects/route.ts
import { getCurrentAuthUser } from '@/lib/auth';
import { db } from '@/lib/db';
import { NextResponse } from 'next/server';
export async function GET() {
const user = await getCurrentAuthUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const projects = await db.projects.findMany({
where: {
OR: [
{ user_id: user.id },
{ project_members: { some: { user_id: user.id } } },
],
},
orderBy: { updated_at: 'desc' },
});
return NextResponse.json({ projects });
}Integration guide
- Set up your auth provider and server-side middleware first.
- Create a single auth utility used by all protected routes.
- Apply route-level checks in APIs and server actions.
- Add role/permission checks before sensitive mutations.
Next step
Explore the full documentation and variants for this pattern.
Open full docs