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 { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
export async function GET() {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const projects = await prisma.project.findMany({
where: { members: { some: { userId } } },
orderBy: { updatedAt: '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