Pular para o conteúdo
Documentação do Next.js PT-BR
Esta página ainda está em inglês. A tradução ainda não foi feita; o conteúdo abaixo é o original de nextjs.org.

unauthorized.jsExperimental

The unauthorized file renders UI when the unauthorized function is invoked.

Before streaming starts, Next.js returns a 401 status code. After streaming starts, the status code remains 200 and the unauthorized UI renders in the response. Next.js injects a <meta name="robots" content="noindex" /> tag in both cases. See Status codes for details.

app/unauthorized.tsx
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>
  )
}

Reference

Props

unauthorized.js components do not accept any props.

Good to know: Next.js sends each unauthorized.js file with every route under its segment, even when unauthorized() is never called, and loads the Client Components it imports on those pages. Prefer Server Components and <Link> there over interactive UI.

Examples

Displaying login UI to unauthenticated users

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

app/dashboard/page.tsx
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>
}
app/unauthorized.tsx
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>
  )
}

Version History

VersionChanges
v15.1.0unauthorized.js introduced.

Próximos passos