Next.js › Authentication & Authorization in Next.js

How do you implement role based authorization, where different users see different content based on their role?

Advanced

Answer

You store a role field on the user's account, such as admin or member, and check that role wherever access needs to be restricted, either in a server component before rendering or in an API route before processing a request, returning a forbidden response or a different view for unauthorized roles.
export default async function AdminPage() {
  const session = await getSession();
  if (session?.user.role !== 'admin') {
    return <p>You do not have access to this page.</p>;
  }
  return <AdminDashboard />;
}
Real-world example A support ticketing system shows regular employees only their own tickets, while showing managers a full view of every ticket, using the same page but with different data based on the logged in user's role.

Common follow-ups: Where should role information be stored, in the session or fetched fresh from the database?;How do you handle a user whose role changes while they are already logged in?