← Back

Authorization with unauthorized()

unauthorized() in Server Components, unauthorized.tsx files, protecting Server Functions.

PublishedMarch 5, 202699 words
Edit

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 />; }
import { unauthorized } from 'next/navigation'; export default function DashboardPage() { if (!canManagePosts()) { unauthorized(); }

The unauthorized.tsx File

From app/dashboard/unauthorized.tsx:

export default function Unauthorized() { return ( <Card className="text-center"> <CardTitle>Unauthorized</CardTitle> <CardDescription

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
return
<
Dashboard
/>
;
}
>
You need to be logged in.
</
CardDescription
>
<
Link
href
=
"
/
"
>
Back to Blog
</
Link
>
</
Card
>
)
;
}
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> ); }
(
{
where
:
{
slug
}
}
)
;
}
export async function deletePost(slug: string) { if (!canManagePosts()) throw new Error('Unauthorized'); await prisma.post.delete({ where: { slug } }); }