Protect authenticated pages
A server-rendered account or dashboard page checks the session and interrupts rendering when no user is signed in.
Next.js 16+ · Function
unauthorized() interrupts rendering for an unauthenticated request and displays Next.js 401 handling. Enable experimental authInterrupts before using it; customize the displayed UI with unauthorized.js.
Enable the experimental authInterrupts option, then call unauthorized() in a render-path server component, server function, or route handler when the request lacks authentication. The call throws a 401 fallback error and stops rendering that route segment; an unauthorized.js boundary can provide the UI.
unauthorized(): neverimport { unauthorized } from 'next/navigation'
export default async function AccountPage() {
const session = await getSession()
if (!session?.user) {
unauthorized()
}
return <h1>Account</h1>
}Calling unauthorized() during server rendering stops the segment and displays the nearest unauthorized UI.
A server-rendered account or dashboard page checks the session and interrupts rendering when no user is signed in.
A Server Function verifies the session before returning protected data and calls unauthorized() when authentication is absent.
A Route Handler rejects an unauthenticated request before streaming begins, allowing a 401 response.
unauthorized() throws a Next.js 401 fallback error and terminates rendering of the route segment where it runs. It is intended for unauthenticated requests and can be used in Server Components, Server Functions, and Route Handlers.
Follow-up: What configuration is required? Enable the experimental authInterrupts option in next.config.js.
The function must execute during rendering or from a function awaited by a component, because it works by throwing. If it is placed in an un-awaited promise, nothing catches the exception and no unauthorized UI is rendered.
Follow-up: How can the response UI be customized? Add an unauthorized.js file in the relevant route segment.
Enable experimental.authInterrupts in next.config.js, then define an unauthorized.js boundary if custom UI is needed. The boundary renders when unauthorized() is invoked.
Follow-up: What happens if the call occurs after streaming begins? The unauthorized UI can render, but the response status remains 200 rather than changing to 401.
unauthorized.jsforbiddenauthInterrupts