Next.jsMedium

What is the forbidden and unauthorized function in Next.js 15?

forbidden() and unauthorized() from next/navigation (added in Next.js 15.1) stop rendering and show a 403 Forbidden or 401 Unauthorized page, rendered from forbidden.tsx and unauthorized.tsx files in app/. They are still experimental in Next.js 16 and require experimental.authInterrupts: true.

What they do

  • unauthorized(): the user is not signed in. Renders app/unauthorized.tsx with a 401 status. Typical content: a login prompt.
  • forbidden(): the user is signed in but lacks permission. Renders app/forbidden.tsx with a 403 status.
  • Both throw special errors (like notFound()), so code after them does not run, and they add a noindex robots tag.

Where you can call them

Server Components, Server Functions and Route Handlers. Not in the root layout.

Why they exist

Before, apps either redirected to /login (losing the URL and status code) or used notFound() (wrong status). These give correct HTTP semantics with a customizable UI, similar to not-found.tsx.

Setup

// next.config.ts
experimental: { authInterrupts: true }

Usage tips

  • Call them from your Data Access Layer helpers, for example requireUser() calls unauthorized() and requireRole("admin") calls forbidden().
  • In Server Functions, they throw and the client receives the error UI; returning a state object may be friendlier for forms.
  • Pair with Proxy redirects for common cases, and keep these as the authoritative check.

Code example

tsx
1// next.config.ts
2// const nextConfig = { experimental: { authInterrupts: true } };
3
4// lib/guards.ts
5import "server-only";
6import { forbidden, unauthorized } from "next/navigation";
7import { verifySession } from "@/lib/dal";
8
9export async function requireRole(role: "admin" | "editor") {
10 const session = await verifySession();
11 if (!session) unauthorized(); // 401 -> app/unauthorized.tsx
12 if (session.role !== role) forbidden(); // 403 -> app/forbidden.tsx
13 return session;
14}
15
16// app/admin/page.tsx
17// export default async function Admin() {
18// await requireRole("admin");
19// return <h1>Admin</h1>;
20// }
21
22// app/forbidden.tsx
23// import Link from "next/link";
24// export default function Forbidden() {
25// return (<main><h1>403: No access</h1><p>Ask an admin for access.</p><Link href="/">Home</Link></main>);
26// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app