Skip to content

unauthorized.js

Source URL: https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized

This feature is currently experimental and subject to change, it is not recommended for production.

The unauthorized file is used to render UI when the unauthorized function is invoked during authentication. Along with allowing you to customize the UI, Next.js will return a 401 status code.

import Login from '@/app/components/Login'
export default function Unauthorized() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}
import Login from '@/app/components/Login'
export default function Unauthorized() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}

unauthorized.js components do not accept any props.

Displaying login UI to unauthenticated users

Section titled “Displaying login UI to unauthenticated users”

You can use unauthorized function to render the unauthorized.js file with a login UI.

import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
export default async function DashboardPage() {
const session = await verifySession()
if (!session) {
unauthorized()
}
return <div>Dashboard</div>
}
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
export default async function DashboardPage() {
const session = await verifySession()
if (!session) {
unauthorized()
}
return <div>Dashboard</div>
}
import Login from '@/app/components/Login'
export default function UnauthorizedPage() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}
import Login from '@/app/components/Login'
export default function UnauthorizedPage() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}
VersionChanges
v15.1.0unauthorized.js introduced.