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. Rendersapp/unauthorized.tsxwith a 401 status. Typical content: a login prompt.forbidden(): the user is signed in but lacks permission. Rendersapp/forbidden.tsxwith a 403 status.- Both throw special errors (like
notFound()), so code after them does not run, and they add anoindexrobots 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()callsunauthorized()andrequireRole("admin")callsforbidden(). - 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.ts2// const nextConfig = { experimental: { authInterrupts: true } };34// lib/guards.ts5import "server-only";6import { forbidden, unauthorized } from "next/navigation";7import { verifySession } from "@/lib/dal";89export async function requireRole(role: "admin" | "editor") {10 const session = await verifySession();11 if (!session) unauthorized(); // 401 -> app/unauthorized.tsx12 if (session.role !== role) forbidden(); // 403 -> app/forbidden.tsx13 return session;14}1516// app/admin/page.tsx17// export default async function Admin() {18// await requireRole("admin");19// return <h1>Admin</h1>;20// }2122// app/forbidden.tsx23// 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.