← Back to blog

Authorization Patterns

Next.js provides unauthorized() for handling authorization in Server Components.

Checking Authorization

import { unauthorized } from 'next/navigation'; export default function DashboardPage() { if (!canManagePosts()) { unauthorized(); } return <Dashboard />; }

The unauthorized.tsx File

From app/dashboard/unauthorized.tsx:

export default function Unauthorized() { return ( <Card className="text-center"> <CardTitle>Unauthorized</CardTitle> <CardDescription>You need to be logged in.</CardDescription> <Link href="/">Back to Blog</Link> </Card> ); }

Protecting Server Functions

Always check authorization in actions too:

export async function deletePost(slug: string) { if (!canManagePosts()) throw new Error('Unauthorized'); await prisma.post.delete({ where: { slug } }); }
March 5, 202699 words