typescriptintermediate
NextAuth Session Check Pattern
Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';
import { authOptions } from '@/lib/auth';
export async function requireAuth() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect('/login');
return session;
}
export async function requireRole(role: string) {
const session = await requireAuth();
if ((session.user as { role?: string }).role !== role) {
redirect('/unauthorized');
}
return session;
}
// Usage in a page:
// export default async function DashboardPage() {
// const session = await requireAuth();
// return <Dashboard user={session.user} />;
// }Sponsored
Try Clerk — Drop-in Auth for Next.js
Use Cases
- Protected pages
- Role-based access
- Dashboard guards
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Cookies and Headers in Server Components
Read and set cookies and headers in Next.js server components and route handlers.
Best for: theme preferences
#nextjs#cookies
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptbeginner
Cached Fetch with Revalidation
Fetch external data in Server Components with time-based revalidation and error boundaries.
Best for: CMS content fetching
#fetch#caching
typescriptintermediate
Parallel Data Fetching in Server Components
Fetch multiple data sources in parallel using Promise.all in Next.js server components for faster page loads.
Best for: dashboard pages
#nextjs#data-fetching