← Back
Edit Post
Title
Description
unauthorized() in Server Components, unauthorized.tsx files, protecting Server Functions.
Content
Markdown supported
# Authorization Patterns Next.js provides `unauthorized()` for handling authorization in Server Components. ## Checking Authorization ```tsx import { unauthorized } from 'next/navigation'; export default function DashboardPage() { if (!canManagePosts()) { unauthorized(); } return <Dashboard />; } ``` ## The unauthorized.tsx File From `app/dashboard/unauthorized.tsx`: ```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: ```tsx export async function deletePost(slug: string) { if (!canManagePosts()) throw new Error('Unauthorized'); await prisma.post.delete({ where: { slug } }); } ```
Published
Save Changes
Cancel