Unverified Commit 0be0ebe5 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: navigation interrupts after streaming has started (notFound, forbidden,…

docs: navigation interrupts after streaming has started (notFound, forbidden, unauthorized) (#95851)

Adds a "Calling `x()` after streaming has started" example to the
`notFound`, `forbidden`, and `unauthorized` references.

- The check lives in the data-access function that loads the data,
inside a `<Suspense>` boundary, so the page shell keeps streaming (blog
post 404, account 401, admin projects 403).
- Documents the status-code trade-off: the interrupt fires after headers
are sent, so the response is a `200`; a `loading.tsx` is part of the
stream, not a way around it; `instant = false` opts the route out of the
shell for a real status code.
- Links the authentication guide's DAL section instead of re-teaching
it, plus a good-to-know on floating promises never rendering the UI.

Docs-only.
parent b79052e0
...@@ -5,9 +5,14 @@ version: experimental ...@@ -5,9 +5,14 @@ version: experimental
related: related:
links: links:
- app/api-reference/file-conventions/forbidden - app/api-reference/file-conventions/forbidden
- app/api-reference/functions/not-found
- app/api-reference/functions/unauthorized
- app/api-reference/config/next-config-js/authInterrupts
--- ---
The `forbidden` function throws an error that renders a Next.js 403 error page. It's useful for handling authorization errors in your application. You can customize the UI using the [`forbidden.js` file](/docs/app/api-reference/file-conventions/forbidden). The `forbidden` function throws an error that renders a Next.js 403 page. It's useful for handling authorization errors in your application. You can customize the UI using the [`forbidden.js` file](/docs/app/api-reference/file-conventions/forbidden).
Invoking `forbidden()` throws a `NEXT_HTTP_ERROR_FALLBACK;403` error and terminates rendering of the route segment where it was thrown. Next.js also injects a `<meta name="robots" content="noindex" />` tag so the page is not indexed. Because it works by throwing, call it in the render path: a component, or a function a component `await`s. A call left in an un-awaited promise throws where nothing catches it, and no forbidden UI renders.
To start using `forbidden`, enable the experimental [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts) configuration option in your `next.config.js` file: To start using `forbidden`, enable the experimental [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts) configuration option in your `next.config.js` file:
...@@ -33,7 +38,7 @@ module.exports = { ...@@ -33,7 +38,7 @@ module.exports = {
`forbidden` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/mutating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route). `forbidden` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/mutating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route).
```tsx filename="app/auth/page.tsx" switcher ```tsx filename="app/admin/page.tsx" switcher
import { verifySession } from '@/app/lib/dal' import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation' import { forbidden } from 'next/navigation'
...@@ -50,7 +55,7 @@ export default async function AdminPage() { ...@@ -50,7 +55,7 @@ export default async function AdminPage() {
} }
``` ```
```jsx filename="app/auth/page.js" switcher ```jsx filename="app/admin/page.js" switcher
import { verifySession } from '@/app/lib/dal' import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation' import { forbidden } from 'next/navigation'
...@@ -70,9 +75,115 @@ export default async function AdminPage() { ...@@ -70,9 +75,115 @@ export default async function AdminPage() {
## Good to know ## Good to know
- The `forbidden` function cannot be called in the [root layout](/docs/app/api-reference/file-conventions/layout#root-layout). - The `forbidden` function cannot be called in the [root layout](/docs/app/api-reference/file-conventions/layout#root-layout).
- You do not need to write `return forbidden()`. It throws (its TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) return type), so execution stops. A `try/catch` around the call suppresses the interrupt and no forbidden UI renders. Use [`unstable_rethrow`](/docs/app/api-reference/functions/unstable_rethrow) to let it through.
- A `forbidden()` left in an un-awaited promise throws where nothing catches it, so no forbidden UI renders. In development the server logs `⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;403`. Always `await` the function that may call it.
## Examples ## Examples
### Calling `forbidden()` after streaming has started
To keep the page's shell and loading UI visible while the session is checked, put the role check in the [Data Access Layer](/docs/app/guides/authentication#creating-a-data-access-layer-dal) function that loads the data, and render it in a component wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The check runs inside the boundary, so the shell streams while the session resolves:
```tsx filename="app/projects/page.tsx" switcher highlight={8}
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
async function getProjects() {
const session = await verifySession()
if (session?.role !== 'admin') {
forbidden()
}
return db.projects.findMany()
}
async function Projects() {
const projects = await getProjects()
return (
<ul>
{projects.map((project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
)
}
export default function ProjectsPage() {
return (
<main>
<h1>Projects</h1>
<Suspense fallback={<p>Loading...</p>}>
<Projects />
</Suspense>
</main>
)
}
```
```jsx filename="app/projects/page.js" switcher highlight={8}
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
async function getProjects() {
const session = await verifySession()
if (session?.role !== 'admin') {
forbidden()
}
return db.projects.findMany()
}
async function Projects() {
const projects = await getProjects()
return (
<ul>
{projects.map((project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
)
}
export default function ProjectsPage() {
return (
<main>
<h1>Projects</h1>
<Suspense fallback={<p>Loading...</p>}>
<Projects />
</Suspense>
</main>
)
}
```
When the session lacks access, `getProjects` calls `forbidden()`, which throws. Because this happens during rendering, the exception propagates to the nearest [`forbidden`](/docs/app/api-reference/file-conventions/forbidden) boundary, which renders in place of the streamed-in content, even though the page shell has already been sent.
Add a `forbidden.tsx` alongside the route to define that UI:
```tsx filename="app/projects/forbidden.tsx" switcher
export default function Forbidden() {
return (
<main>
<h1>403 - Forbidden</h1>
<p>You don't have access to this page.</p>
</main>
)
}
```
```jsx filename="app/projects/forbidden.js" switcher
export default function Forbidden() {
return (
<main>
<h1>403 - Forbidden</h1>
<p>You don't have access to this page.</p>
</main>
)
}
```
The trade-off is the HTTP status code. Because the check runs inside the `<Suspense>` boundary, the response has already begun streaming as a `200`, and the status can't change once streaming has started. This is usually fine for a page, where the user sees the `forbidden` UI regardless. To return a real `403` status, the check has to run before the response streams. With [Cache Components](/docs/app/getting-started/caching), every dynamic route streams a static shell first, so run that check in [`proxy`](/docs/app/api-reference/file-conventions/proxy) instead. See [Status codes](/docs/app/api-reference/file-conventions/loading#status-codes).
### Role-based route protection ### Role-based route protection
You can use `forbidden` to restrict access to certain routes based on user roles. This ensures that users who are authenticated but lack the required permissions cannot access the route. You can use `forbidden` to restrict access to certain routes based on user roles. This ensures that users who are authenticated but lack the required permissions cannot access the route.
......
--- ---
title: notFound title: notFound
description: API Reference for the notFound function. description: API Reference for the notFound function.
related:
links:
- app/api-reference/file-conventions/not-found
- app/api-reference/functions/forbidden
- app/api-reference/functions/unauthorized
--- ---
The `notFound` function allows you to render the [`not-found file`](/docs/app/api-reference/file-conventions/not-found) within a route segment as well as inject a [`<meta name="robots" content="noindex" />`](/docs/app/api-reference/file-conventions/loading#status-codes) tag for search engines. The `notFound` function throws an error that renders a Next.js 404 page. It's useful for handling missing resources in your application. You can customize the UI using the [`not-found.js` file](/docs/app/api-reference/file-conventions/not-found).
## `notFound()` Invoking `notFound()` throws a `NEXT_HTTP_ERROR_FALLBACK;404` error and terminates rendering of the route segment where it was thrown. Next.js also injects a `<meta name="robots" content="noindex" />` tag so the page is not indexed. Because it works by throwing, call it in the render path: a component, or a function a component `await`s. A call left in an un-awaited promise throws where nothing catches it, and no not-found UI renders (in development the server logs `⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;404`).
Invoking the `notFound()` function throws a `NEXT_HTTP_ERROR_FALLBACK;404` error and terminates rendering of the route segment in which it was thrown. Specifying a [**not-found** file](/docs/app/api-reference/file-conventions/not-found) allows you to gracefully handle such errors by rendering a Not Found UI within the segment. `notFound()` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/mutating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route).
```jsx filename="app/user/[id]/page.js" ```tsx filename="app/user/[id]/page.tsx" switcher
import { notFound } from 'next/navigation'
async function fetchUser(id: string) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const user = await fetchUser(id)
if (!user) {
notFound()
}
// ...
}
```
```jsx filename="app/user/[id]/page.js" switcher
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
async function fetchUser(id) { async function fetchUser(id) {
...@@ -30,7 +60,172 @@ export default async function Profile({ params }) { ...@@ -30,7 +60,172 @@ export default async function Profile({ params }) {
} }
``` ```
> **Good to know**: `notFound()` does not require you to use `return notFound()` due to using the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type. ## Good to know
You do not need to write `return notFound()`. Calling it is enough, because it throws an exception that stops function execution. TypeScript understands this from its [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) return type, so a value you check first stays narrowed afterward:
```tsx
// fetchUser resolves to a user object, or undefined
const user = await fetchUser(id)
if (!user) {
notFound()
}
// user is defined here
return <Profile user={user} />
```
Like any exception, it travels up the call stack until something catches it. A `try/catch` around the call suppresses it, and the not-found UI won't render. If you need to catch errors near the call, use [`unstable_rethrow`](/docs/app/api-reference/functions/unstable_rethrow) to let the interrupt through first.
## Examples
### Calling `notFound()` after streaming has started
To keep a page's shell and loading UI visible while data loads, do the existence check inside a component wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense) instead of blocking the whole route. The idiomatic place for the check is the data-access function itself, awaited by the component that needs the data:
```tsx filename="app/blog/[slug]/page.tsx" switcher highlight={8}
import { Suspense } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
async function getPost(slug: string) {
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (res.status === 404) {
notFound()
}
if (!res.ok) {
throw new Error(`Failed to load post: ${res.status}`)
}
return res.json()
}
async function Article({ slug }: { slug: string }) {
const post = await getPost(slug)
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
)
}
export default async function PostPage({ params }: PageProps<'/blog/[slug]'>) {
const { slug } = await params
return (
<section>
<Link href="/blog">Blog</Link>
<Suspense fallback={<p>Loading...</p>}>
<Article slug={slug} />
</Suspense>
</section>
)
}
```
```jsx filename="app/blog/[slug]/page.js" switcher highlight={8}
import { Suspense } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
async function getPost(slug) {
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (res.status === 404) {
notFound()
}
if (!res.ok) {
throw new Error(`Failed to load post: ${res.status}`)
}
return res.json()
}
async function Article({ slug }) {
const post = await getPost(slug)
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
)
}
export default async function PostPage({ params }) {
const { slug } = await params
return (
<section>
<Link href="/blog">Blog</Link>
<Suspense fallback={<p>Loading...</p>}>
<Article slug={slug} />
</Suspense>
</section>
)
}
```
When the post doesn't exist, `getPost` calls `notFound()`, which throws. Because this happens during rendering, the exception propagates to the nearest [`not-found`](/docs/app/api-reference/file-conventions/not-found) boundary, which renders in place of the streamed-in content, even though the page shell has already been sent.
Add a `not-found.tsx` alongside the route to define that UI. Without one, the nearest parent `not-found` boundary renders, falling back to Next.js's default 404 page:
```tsx filename="app/blog/[slug]/not-found.tsx" switcher
export default function NotFound() {
return (
<section>
<h1>Post not found</h1>
<p>The post you're looking for doesn't exist.</p>
</section>
)
}
```
```jsx filename="app/blog/[slug]/not-found.js" switcher
export default function NotFound() {
return (
<section>
<h1>Post not found</h1>
<p>The post you're looking for doesn't exist.</p>
</section>
)
}
```
The trade-off is the HTTP status code. Because the check runs inside the `<Suspense>` boundary, the response has already begun streaming as a `200`, and the status can't change once streaming has started. The `noindex` tag keeps a soft 404 out of search results. To return a real `404` status, the resource has to be checked before the response streams. With [Cache Components](/docs/app/getting-started/caching), every dynamic route streams a static shell first, so run that check in [`proxy`](/docs/app/api-reference/file-conventions/proxy) instead. See [Status codes](/docs/app/api-reference/file-conventions/loading#status-codes).
### Serving a 404 from a Route Handler
`notFound()` also works in a [Route Handler](/docs/app/api-reference/file-conventions/route), where it serves a `404` to the caller.
```tsx filename="app/api/posts/[slug]/route.ts" switcher
import { NextResponse } from 'next/server'
import { notFound } from 'next/navigation'
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[slug]'>
) {
const { slug } = await params
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (!res.ok) {
notFound()
}
return NextResponse.json(await res.json())
}
```
```jsx filename="app/api/posts/[slug]/route.js" switcher
import { NextResponse } from 'next/server'
import { notFound } from 'next/navigation'
export async function GET(request, { params }) {
const { slug } = await params
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (!res.ok) {
notFound()
}
return NextResponse.json(await res.json())
}
```
## Version History ## Version History
......
...@@ -5,9 +5,14 @@ version: experimental ...@@ -5,9 +5,14 @@ version: experimental
related: related:
links: links:
- app/api-reference/file-conventions/unauthorized - app/api-reference/file-conventions/unauthorized
- app/api-reference/functions/not-found
- app/api-reference/functions/forbidden
- app/api-reference/config/next-config-js/authInterrupts
--- ---
The `unauthorized` 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 the [`unauthorized.js` file](/docs/app/api-reference/file-conventions/unauthorized). The `unauthorized` function throws an error that renders a Next.js 401 page. It's useful for handling authentication errors, when a request is not signed in. You can customize the UI using the [`unauthorized.js` file](/docs/app/api-reference/file-conventions/unauthorized).
Invoking `unauthorized()` throws a `NEXT_HTTP_ERROR_FALLBACK;401` error and terminates rendering of the route segment where it was thrown. Next.js also injects a `<meta name="robots" content="noindex" />` tag so the page is not indexed. Because it works by throwing, call it in the render path: a component, or a function a component `await`s. A call left in an un-awaited promise throws where nothing catches it, and no unauthorized UI renders.
To start using `unauthorized`, enable the experimental [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts) configuration option in your `next.config.js` file: To start using `unauthorized`, enable the experimental [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts) configuration option in your `next.config.js` file:
...@@ -78,9 +83,111 @@ export default async function DashboardPage() { ...@@ -78,9 +83,111 @@ export default async function DashboardPage() {
## Good to know ## Good to know
- The `unauthorized` function cannot be called in the [root layout](/docs/app/api-reference/file-conventions/layout#root-layout). - The `unauthorized` function cannot be called in the [root layout](/docs/app/api-reference/file-conventions/layout#root-layout).
- You do not need to write `return unauthorized()`. It throws (its TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) return type), so execution stops. A `try/catch` around the call suppresses the interrupt and no unauthorized UI renders. Use [`unstable_rethrow`](/docs/app/api-reference/functions/unstable_rethrow) to let it through.
- An `unauthorized()` left in an un-awaited promise throws where nothing catches it, so no unauthorized UI renders. In development the server logs `⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;401`. Always `await` the function that may call it.
## Examples ## Examples
### Calling `unauthorized()` after streaming has started
To keep the page's shell and loading UI visible while the session is verified, put the auth check in the [Data Access Layer](/docs/app/guides/authentication#creating-a-data-access-layer-dal) function that loads the data, and render it in a component wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense). The check runs inside the boundary, so the shell streams while the session resolves:
```tsx filename="app/account/page.tsx" switcher highlight={8}
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
async function getAccount() {
const session = await verifySession()
if (!session) {
unauthorized()
}
return db.accounts.findByUserId(session.userId)
}
async function AccountDetails() {
const account = await getAccount()
return <p>Signed in as {account.email}</p>
}
export default function AccountPage() {
return (
<main>
<h1>Account</h1>
<Suspense fallback={<p>Loading...</p>}>
<AccountDetails />
</Suspense>
</main>
)
}
```
```jsx filename="app/account/page.js" switcher highlight={8}
import { Suspense } from 'react'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
async function getAccount() {
const session = await verifySession()
if (!session) {
unauthorized()
}
return db.accounts.findByUserId(session.userId)
}
async function AccountDetails() {
const account = await getAccount()
return <p>Signed in as {account.email}</p>
}
export default function AccountPage() {
return (
<main>
<h1>Account</h1>
<Suspense fallback={<p>Loading...</p>}>
<AccountDetails />
</Suspense>
</main>
)
}
```
When the request isn't signed in, `getAccount` calls `unauthorized()`, which throws. Because this happens during rendering, the exception propagates to the nearest [`unauthorized`](/docs/app/api-reference/file-conventions/unauthorized) boundary, which renders in place of the streamed-in content, even though the page shell has already been sent.
Add an `unauthorized.tsx` alongside the route to define that UI:
```tsx filename="app/account/unauthorized.tsx" switcher
import Link from 'next/link'
export default function Unauthorized() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>
Please <Link href="/login">sign in</Link> to view your account.
</p>
</main>
)
}
```
```jsx filename="app/account/unauthorized.js" switcher
import Link from 'next/link'
export default function Unauthorized() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>
Please <Link href="/login">sign in</Link> to view your account.
</p>
</main>
)
}
```
The trade-off is the HTTP status code. Because the check runs inside the `<Suspense>` boundary, the response has already begun streaming as a `200`, and the status can't change once streaming has started. This is usually fine for a page, where the user sees the `unauthorized` UI regardless. To return a real `401` status, the check has to run before the response streams. With [Cache Components](/docs/app/getting-started/caching), every dynamic route streams a static shell first, so run that check in [`proxy`](/docs/app/api-reference/file-conventions/proxy) instead. See [Status codes](/docs/app/api-reference/file-conventions/loading#status-codes).
### Displaying login UI to unauthenticated users ### Displaying login UI to unauthenticated users
You can use `unauthorized` function to display the `unauthorized.js` file with a login UI. You can use `unauthorized` function to display the `unauthorized.js` file with a login UI.
......
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