NextAuth Session Check Pattern
Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.
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.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Cached Fetch with Revalidation
Fetch external data in Server Components with time-based revalidation and error boundaries.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
JWT Refresh Token Rotation
Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.