unauthorized
This feature is currently experimental and subject to change, it's not recommended for production. Try it out and share your feedback onGitHub.
Last updated June 16, 2025
Theunauthorized function throws an error that renders a Next.js 401 error page. It's useful for handling authorization errors in your application. You can customize the UI using theunauthorized.js file.
To start usingunauthorized, enable the experimentalauthInterrupts configuration option in yournext.config.js file:
next.config.ts
importtype { NextConfig }from'next'constnextConfig:NextConfig= { experimental: { authInterrupts:true, },}exportdefault nextConfigunauthorized can be invoked inServer Components,Server Actions, andRoute Handlers.
app/dashboard/page.tsx
import { verifySession }from'@/app/lib/dal'import { unauthorized }from'next/navigation'exportdefaultasyncfunctionDashboardPage() {constsession=awaitverifySession()if (!session) {unauthorized() }// Render thedashboard for authenticated usersreturn ( <main> <h1>Welcome to the Dashboard</h1> <p>Hi, {session.user.name}.</p> </main> )}Good to know
- The
unauthorizedfunction cannot be called in theroot layout.
Examples
Displaying login UI to unauthenticated users
You can useunauthorized function to display theunauthorized.js file with a login UI.
app/dashboard/page.tsx
import { verifySession }from'@/app/lib/dal'import { unauthorized }from'next/navigation'exportdefaultasyncfunctionDashboardPage() {constsession=awaitverifySession()if (!session) {unauthorized() }return <div>Dashboard</div>}app/unauthorized.tsx
import Loginfrom'@/app/components/Login'exportdefaultfunctionUnauthorizedPage() {return ( <main> <h1>401 - Unauthorized</h1> <p>Please log in to access this page.</p> <Login /> </main> )}Mutations with Server Actions
You can invokeunauthorized in Server Actions to ensure only authenticated users can perform specific mutations.
app/actions/update-profile.ts
'use server'import { verifySession }from'@/app/lib/dal'import { unauthorized }from'next/navigation'import dbfrom'@/app/lib/db'exportasyncfunctionupdateProfile(data:FormData) {constsession=awaitverifySession()// If the user is not authenticated, return a 401if (!session) {unauthorized() }// Proceed with mutation// ...}Fetching data with Route Handlers
You can useunauthorized in Route Handlers to ensure only authenticated users can access the endpoint.
app/api/profile/route.ts
import { NextRequest, NextResponse }from'next/server'import { verifySession }from'@/app/lib/dal'import { unauthorized }from'next/navigation'exportasyncfunctionGET(req:NextRequest):Promise<NextResponse> {// Verify the user's sessionconstsession=awaitverifySession()// If no session exists, return a 401 and render unauthorized.tsxif (!session) {unauthorized() }// Fetch data// ...}Version History
| Version | Changes |
|---|---|
v15.1.0 | unauthorized introduced. |
Was this helpful?