Next.js Authentication details how to secure route segments, protect Server Actions, and manage user login sessions using Auth.js (NextAuth.js) and JSON Web Tokens (JWTs).
Authentication in Next.js relies on securing both server-side rendered routes and client-side component views.
Server Components can check active user sessions securely on the server without sending token logic to the browser:
// app/dashboard/page.tsx
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth'; // Custom auth provider module
export default async function DashboardPage() {
const session = await getSession();
if (!session) {
redirect('/login');
}
return (
<div className="p-6">
<h1 className="text-2xl font-bold">Welcome Back, {session.user.name}</h1>
<p className="text-gray-600">Email: {session.user.email}</p>
</div>
);
}
Always check user permissions inside Server Actions before running database operations:
// app/actions/deletePost.ts
'use server';
import { getSession } from '@/lib/auth';
export async function deletePost(postId: string) {
const session = await getSession();
if (!session || session.user.role !== 'admin') {
throw new Error('Unauthorized: You must be an administrator to perform this action.');
}
// Execute database record deletion
await db.post.delete({ where: { id: postId } });
}
document.cookie.Next.js authentication combines secure HTTP-only cookies with server-side session checks. Server Components and middleware ensure protected routes stay safe from unauthorized access.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With