Next.js course Β· Module 9: Integrations and Advanced Features
forbidden() and unauthorized() - New error handling functions
In this lesson10
Two people try to enter the administrative sector of Metropolis Quantum 2150. The first has no pass at all, the second has a guest pass. Both must be stopped, but each with a different message: the first should go to the registration desk, the second should learn that this sector is not for them. In HTTP that is the difference between status 401 and 403. You will learn the forbidden() and unauthorized() functions, introduced in Next.js 15.1, which simplify handling authorization and authentication errors.
Problem: Handling 401/403 errors by hand
Previously, handling authorization errors required manually creating a Response object with a status code in every place that checks the session:
// Old, verbose approach
export async function GET(request: Request) {
const session = await getSession();
if (!session) {
return new Response('Unauthorized', { status: 401 });
}
if (!session.user.isAdmin) {
return new Response('Forbidden', { status: 403 });
}
return Response.json(await getAdminData());
}This pattern works in a Route Handler, but you cannot return a Response object from a page component, and the messages drift apart across the whole application.
Solution: forbidden() and unauthorized()
unauthorized() - 401 error
The unauthorized() function imported from next/navigation interrupts rendering of the segment, returns status 401 and shows the UI from the unauthorized.tsx file:
// app/api/profile/route.ts
import { unauthorized } from 'next/navigation';
import { getSession } from '@/lib/auth';
export async function GET(request: Request) {
const session = await getSession();
if (!session) {
unauthorized(); // Throws a 401 error
}
return Response.json(session.user);
}You do not write return unauthorized(), because the function throws and has the never return type. Thanks to that, TypeScript knows that after the condition session definitely exists.
forbidden() - 403 error
The forbidden() function works the same way, but it means "I know who you are, and you have no access". It renders the UI from the forbidden.tsx file:
// app/api/admin/users/route.ts
import { forbidden, unauthorized } from 'next/navigation';
import { getSession } from '@/lib/auth';
export async function GET(request: Request) {
const session = await getSession();
if (!session) {
unauthorized(); // 401 - not logged in
}
if (session.user.role !== 'admin') {
forbidden(); // 403 - missing permissions
}
return Response.json(await getAllUsers());
}The order of checks matters: identity first (401), then permissions (403). Both functions work in Server Components, Server Actions and Route Handlers.
Enabling the functions
In Next.js 16 both functions are still experimental and the docs do not recommend them for production yet. You enable them with the authInterrupts option:
// next.config.js
module.exports = {
experimental: {
authInterrupts: true,
},
};Without this flag calling the functions ends in an error, so add it before you start experimenting.
Creating error pages
unauthorized.tsx - 401 page
The unauthorized.tsx file in the app directory is a regular React component that Next.js displays after unauthorized() is called:
// app/unauthorized.tsx
export default function UnauthorizedPage() {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-900">
<div className="text-center">
<h1 className="text-6xl font-bold text-red-500 mb-4">401</h1>
<h2 className="text-2xl text-white mb-4">Authorization required</h2>
<p className="text-gray-400 mb-8">
You must log in to access this page.
</p>
<a
href="/login"
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
Log in
</a>
</div>
</div>
);
}The most important part is the login link, because a user without a session needs a way forward, not just a message.
forbidden.tsx - 403 page
The 403 page has a different role: logging in will not help, so we offer a way back to the home page:
// app/forbidden.tsx
export default function ForbiddenPage() {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-900">
<div className="text-center">
<h1 className="text-6xl font-bold text-yellow-500 mb-4">403</h1>
<h2 className="text-2xl text-white mb-4">Access denied</h2>
<p className="text-gray-400 mb-8">
You do not have permission to view this page.
</p>
<a
href="/"
className="px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700"
>
Back to home page
</a>
</div>
</div>
);
}Next.js adds a noindex tag to both pages, so search engines do not index them.
Nested error pages
You can create error pages specific to segments. Next.js picks the nearest file up the directory tree:
app/
βββ unauthorized.tsx # Global 401 page
βββ forbidden.tsx # Global 403 page
βββ admin/
β βββ unauthorized.tsx # 401 for /admin/*
β βββ forbidden.tsx # 403 for /admin/*
β βββ page.tsx
βββ dashboard/
βββ forbidden.tsx # 403 for /dashboard/*
βββ page.tsxWith no unauthorized.tsx in dashboard/, the global 401 page from the app directory applies to that section.
Example - Admin forbidden.tsx
An error page can be an async Server Component and read the session to address the user by name:
// app/admin/forbidden.tsx
import { getSession } from '@/lib/auth';
export default async function AdminForbiddenPage() {
const session = await getSession();
return (
<div className="min-h-screen flex items-center justify-center bg-slate-900">
<div className="max-w-md text-center p-8 bg-slate-800 rounded-xl">
<div className="text-6xl mb-4">β</div>
<h1 className="text-2xl font-bold text-white mb-4">
Administrator area
</h1>
<p className="text-gray-400 mb-6">
Hi {session?.user?.name}! Unfortunately, your account does not have
administrator permissions. Contact the system administrator if you
believe this is a mistake.
</p>
<div className="flex gap-4 justify-center">
<a
href="/dashboard"
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
User panel
</a>
<a
href="/support"
className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
>
Contact support
</a>
</div>
</div>
</div>
);
}The user knows who they are logged in as and where they can go next: to their own panel or to support.
Usage in Server Components
In a page component you put the checks at the very beginning, before fetching data:
// app/admin/page.tsx
import { forbidden, unauthorized } from 'next/navigation';
import { getSession } from '@/lib/auth';
export default async function AdminPage() {
const session = await getSession();
if (!session) {
unauthorized();
}
if (!session.user.permissions.includes('admin:access')) {
forbidden();
}
const adminData = await getAdminDashboard();
return (
<div className="admin-dashboard">
<h1>Administrator Panel</h1>
<AdminStats data={adminData} />
</div>
);
}If the user lacks the admin:access permission, getAdminDashboard never runs. Just remember that forbidden() cannot be called in the root layout of the app. Also beware of try/catch around these functions: it swallows the interrupt and the error page will not show, unless you let it through with unstable_rethrow.
Usage in Middleware
Middleware runs before rendering, so it can reject a request the fastest. In Next.js 16 the middleware.ts file was renamed to proxy.ts and the function to proxy, but the logic stays the same:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
const path = request.nextUrl.pathname;
// Paths requiring login
if (path.startsWith('/dashboard')) {
if (!token) {
// Redirect to the unauthorized page
return NextResponse.rewrite(new URL('/unauthorized', request.url));
}
}
// Paths requiring the admin role
if (path.startsWith('/admin')) {
if (!token) {
return NextResponse.rewrite(new URL('/unauthorized', request.url));
}
if (token.role !== 'admin') {
return NextResponse.rewrite(new URL('/forbidden', request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*'],
};NextResponse.rewrite shows the content of another address without changing the URL in the browser bar. Note: the unauthorized.tsx and forbidden.tsx files are not routes, so such a rewrite needs regular pages at /unauthorized and /forbidden. Middleware only checks the token, and you still repeat the real authorization close to the data.
Practical example - Role system
Instead of repeating the same conditions in every file, gather them in small helper functions. The Permission type lists the allowed permissions:
// lib/auth-utils.ts
import { forbidden, unauthorized } from 'next/navigation';
import { getSession } from '@/lib/auth';
type Permission = 'read' | 'write' | 'delete' | 'admin';
export async function requireAuth() {
const session = await getSession();
if (!session) {
unauthorized();
}
return session;
}
export async function requirePermission(permission: Permission) {
const session = await requireAuth();
if (!session.user.permissions.includes(permission)) {
forbidden();
}
return session;
}
export async function requireRole(role: string) {
const session = await requireAuth();
if (session.user.role !== role) {
forbidden();
}
return session;
}
export async function requireAdmin() {
return requireRole('admin');
}requireAuth handles 401, while requirePermission and requireRole add 403. Each returns the session, so the calling code has immediate access to the user.
Usage in components:
// app/admin/users/page.tsx
import { requireAdmin } from '@/lib/auth-utils';
export default async function AdminUsersPage() {
const session = await requireAdmin(); // Will throw 401 or 403 if needed
const users = await getAllUsers();
return <UserManagement users={users} currentAdmin={session.user} />;
}One line replaces two conditions. The page stays readable, and the access rules live in a single file.
The same helper protects a Route Handler that deletes a post:
// app/api/posts/[id]/route.ts
import { requirePermission } from '@/lib/auth-utils';
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
await requirePermission('delete'); // Will throw 401 or 403 if needed
await deletePost((await params).id);
return Response.json({ success: true });
}The API endpoint and the page use identical rules, so there is no risk that one of them forgets the check.
Differences between unauthorized() and forbidden()
| Aspect | unauthorized() | forbidden() |
|---|---|---|
| HTTP code | 401 Unauthorized | 403 Forbidden |
| Meaning | No authentication | No authorization |
| When to use | User not logged in | User logged in, but without permissions |
| Error page | unauthorized.tsx | forbidden.tsx |
| Typical action | Redirect to login | Information about missing access |
One trap: if the check happens in a component inside Suspense, the response has already started streaming with status 200. The user will see the correct error page, but the HTTP code will not change. If you need a real 401 or 403, check before streaming, for example in proxy.
Summary
The forbidden() and unauthorized() functions in Next.js 15.1+:
- Simplify code - one line instead of creating a Response
- Standardize handling - consistent behavior across the application
- Support SSR - they work in Server Components, Server Actions and Route Handlers
- Are configurable - custom error pages per segment
My advice: keep access rules in a single helper file and always check permissions close to the data, not only in middleware. In the next lesson you will learn after(), which runs code after the response has been sent.
Remember: 401 says "introduce yourself", 403 says "I know you, but you are not getting in" - the guardians of the Metropolis never mix them up.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Create Article content type with title, content, slug fields
interface ArticleContentType {
title: string;
content: string;
slug: string;
author?: string;
publishedAt?: string;
}
export default function ContentTypeBuilder() {
const [article, setArticle] = useState<ArticleContentType>({
title: '', content: '', slug: '',
});
const [articles, setArticles] = useState<ArticleContentType[]>([]);
// TODO: Implement auto-generating slug from title
// const generateSlug = (title: string) => title.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
// TODO: Implement handleSave - add article to list
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Article Content Type</h1>
<form style={{ maxWidth: 500 }}>
{/* TODO: Title input with auto-slug generation */}
{/* TODO: Textarea content */}
{/* TODO: Display generated slug */}
{/* TODO: "Save" button */}
</form>
{/* TODO: List of saved articles */}
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What do the new forbidden() and unauthorized() functions introduced in Next.js 15 do?