Unverified Commit 8051552d authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: recommend auth interruption APIs in error handling (#99696)

## Summary

- Recommend `unauthorized()` for unauthenticated requests and
`forbidden()` for authenticated users without access.
- Add `Suspense` boundaries around the request-time reads in the
existing `notFound()` example and the new authentication example so both
patterns work with Cache Components.
- Add corresponding `unauthorized` and `forbidden` fallback UI examples
and clarify when to use `redirect()` for sign-in flows.
- Document eager fallback rendering consistently across the `error.js`,
`not-found.js`, `unauthorized.js`, and `forbidden.js` references, with
links between the related conventions.

This builds on #99689, which stabilizes the authentication interruption
APIs.

## Verification

- `pnpm prettier --with-node-modules --ignore-path .prettierignore
--write docs/01-app/01-getting-started/10-error-handling.mdx
docs/01-app/03-api-reference/03-file-conventions/error.mdx
docs/01-app/03-api-reference/03-file-conventions/not-found.mdx
docs/01-app/03-api-reference/03-file-conventions/forbidden.mdx
docs/01-app/03-api-reference/03-file-conventions/unauthorized.mdx`
- `pnpm exec eslint --config eslint.config.mjs --fix
docs/01-app/01-getting-started/10-error-handling.mdx
docs/01-app/03-api-reference/03-file-conventions/error.mdx
docs/01-app/03-api-reference/03-file-conventions/not-found.mdx
docs/01-app/03-api-reference/03-file-conventions/forbidden.mdx
docs/01-app/03-api-reference/03-file-conventions/unauthorized.mdx`
- `NO_UPDATE_NOTIFIER=1 pnpm exec alex
docs/01-app/01-getting-started/10-error-handling.mdx
docs/01-app/03-api-reference/03-file-conventions/error.mdx
docs/01-app/03-api-reference/03-file-conventions/not-found.mdx
docs/01-app/03-api-reference/03-file-conventions/forbidden.mdx
docs/01-app/03-api-reference/03-file-conventions/unauthorized.mdx
--quiet`
- Not run: framework tests (documentation-only change)

<!-- NEXT_JS_LLM -->
parent 1c821e2d
......@@ -10,6 +10,10 @@ related:
- app/api-reference/functions/catchError
- app/api-reference/functions/not-found
- app/api-reference/file-conventions/not-found
- app/api-reference/functions/unauthorized
- app/api-reference/file-conventions/unauthorized
- app/api-reference/functions/forbidden
- app/api-reference/file-conventions/forbidden
---
Errors can be divided into two categories: [expected errors](#handling-expected-errors) and [uncaught exceptions](#handling-uncaught-exceptions). This page will walk you through how you can handle these errors in your Next.js application.
......@@ -151,14 +155,23 @@ export default async function Page() {
You can call the [`notFound`](/docs/app/api-reference/functions/not-found) function within a route segment and use the [`not-found.js`](/docs/app/api-reference/file-conventions/not-found) file to show a 404 UI.
```tsx filename="app/blog/[slug]/page.tsx" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getPostBySlug } from '@/lib/posts'
export default async function Page({
params,
}: {
type Props = {
params: Promise<{ slug: string }>
}) {
}
export default function Page({ params }: Props) {
return (
<Suspense fallback={<p>Loading...</p>}>
<Post params={params} />
</Suspense>
)
}
async function Post({ params }: Props) {
const { slug } = await params
const post = getPostBySlug(slug)
......@@ -171,10 +184,19 @@ export default async function Page({
```
```jsx filename="app/blog/[slug]/page.js" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getPostBySlug } from '@/lib/posts'
export default async function Page({ params }) {
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<Post params={params} />
</Suspense>
)
}
async function Post({ params }) {
const { slug } = await params
const post = getPostBySlug(slug)
......@@ -186,6 +208,8 @@ export default async function Page({ params }) {
}
```
The `<Suspense>` boundary lets Next.js prerender the route shell while it waits for request-time route parameters.
```tsx filename="app/blog/[slug]/not-found.tsx" switcher
export default function NotFound() {
return <div>404 - Page Not Found</div>
......@@ -198,6 +222,116 @@ export default function NotFound() {
}
```
### Unauthorized and forbidden
Use [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated and [`forbidden()`](/docs/app/api-reference/functions/forbidden) when an authenticated user does not have access to a resource. Next.js stops rendering the route segment and shows the closest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) or [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden) file.
```tsx filename="app/admin/page.tsx" switcher
import { Suspense } from 'react'
import { forbidden, unauthorized } from 'next/navigation'
import { getSession } from '@/app/lib/session'
export default function AdminPage() {
return (
<Suspense fallback={<p>Loading...</p>}>
<AdminContent />
</Suspense>
)
}
async function AdminContent() {
const session = await getSession()
if (!session?.user) {
unauthorized()
}
if (session.user.role !== 'admin') {
forbidden()
}
return <h1>Admin dashboard</h1>
}
```
```jsx filename="app/admin/page.js" switcher
import { Suspense } from 'react'
import { forbidden, unauthorized } from 'next/navigation'
import { getSession } from '@/app/lib/session'
export default function AdminPage() {
return (
<Suspense fallback={<p>Loading...</p>}>
<AdminContent />
</Suspense>
)
}
async function AdminContent() {
const session = await getSession()
if (!session?.user) {
unauthorized()
}
if (session.user.role !== 'admin') {
forbidden()
}
return <h1>Admin dashboard</h1>
}
```
The `<Suspense>` boundary lets Next.js prerender the route shell while it waits for request-time session data.
Add `unauthorized.tsx` and `forbidden.tsx` to the route segment to customize each fallback:
```tsx filename="app/admin/unauthorized.tsx" switcher
export default function Unauthorized() {
return (
<main>
<h1>Unauthorized</h1>
<p>You must sign in to access this page.</p>
</main>
)
}
```
```jsx filename="app/admin/unauthorized.js" switcher
export default function Unauthorized() {
return (
<main>
<h1>Unauthorized</h1>
<p>You must sign in to access this page.</p>
</main>
)
}
```
```tsx filename="app/admin/forbidden.tsx" switcher
export default function Forbidden() {
return (
<main>
<h1>Forbidden</h1>
<p>You do not have permission to access this page.</p>
</main>
)
}
```
```jsx filename="app/admin/forbidden.js" switcher
export default function Forbidden() {
return (
<main>
<h1>Forbidden</h1>
<p>You do not have permission to access this page.</p>
</main>
)
}
```
Use [`redirect()`](/docs/app/api-reference/functions/redirect) instead when you want to send an unauthenticated user to a sign-in flow.
## Handling uncaught exceptions
Uncaught exceptions are unexpected errors that indicate bugs or issues that should not occur during the normal flow of your application. These should be handled by throwing errors, which will then be caught by error boundaries.
......
......@@ -9,6 +9,8 @@ related:
An **error** file allows you to handle unexpected runtime errors and display fallback UI.
> **Good to know:** Next.js currently renders and sends the `error.js` fallback as part of a normal page render, even when an error is not thrown. Keep this fallback lightweight. The same eager behavior applies to [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized), and [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden).
<Image
alt="error.js special file"
srcLight="/docs/light/error-special-file.png"
......
......@@ -10,6 +10,8 @@ The **forbidden** file renders UI when the [`forbidden`](/docs/app/api-reference
Before streaming starts, Next.js returns a `403` status code. After streaming starts, the status code remains `200` and the forbidden UI renders in the response. Next.js injects a `<meta name="robots" content="noindex" />` tag in both cases. See [Status codes](/docs/app/api-reference/file-conventions/loading#status-codes) for details.
> **Good to know:** Next.js currently renders and sends the `forbidden.js` fallback as part of a normal page render, even when `forbidden()` is not called. Keep this fallback lightweight. The same eager behavior applies to [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized).
```tsx filename="app/forbidden.tsx" switcher
import Link from 'next/link'
......
......@@ -14,6 +14,8 @@ The **not-found** file renders UI when the [`notFound`](/docs/app/api-reference/
Before streaming starts, Next.js returns a `404` status code. After streaming starts, the status code remains `200` and the not-found UI renders in the response. Next.js injects a `<meta name="robots" content="noindex" />` tag in both cases. See [Status codes](/docs/app/api-reference/file-conventions/loading#status-codes) for details.
> **Good to know:** Next.js currently renders and sends the `not-found.js` fallback as part of a normal page render, even when `notFound()` is not called. Keep this fallback lightweight. The same eager behavior applies to [`error.js`](/docs/app/api-reference/file-conventions/error), [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized), and [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden).
```tsx filename="app/not-found.tsx" switcher
import Link from 'next/link'
......
......@@ -10,6 +10,8 @@ The **unauthorized** file renders UI when the [`unauthorized`](/docs/app/api-ref
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](/docs/app/api-reference/file-conventions/loading#status-codes) for details.
> **Good to know:** Next.js currently renders and sends the `unauthorized.js` fallback as part of a normal page render, even when `unauthorized()` is not called. Keep this fallback lightweight. The same eager behavior applies to [`error.js`](/docs/app/api-reference/file-conventions/error), [`not-found.js`](/docs/app/api-reference/file-conventions/not-found), and [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden).
```tsx filename="app/unauthorized.tsx" switcher
import Login from '@/app/components/Login'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment