Unverified Commit 5b106049 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Revert stabilization of `forbidden()` and `unauthorized()` (#99734)

Stabilizing `forbidden()` and `unauthorized()` means the built-in 403
and 401 fallbacks are rendered into every page's payload, even for apps
that don't define `forbidden.tsx` or `unauthorized.tsx`. On a fresh
create-next-app that's about 2.3KB of uncompressed HTML per page (~125
bytes gzipped).

I knew about the regression but I forgot that it applied to every app
and every page, rather than just those that use `forbidden.tsx` or
`unauthorized.tsx`. To avoid blocking the 16.4 release, we'll keep this
feature in experimental for now until we fix the implementation to
render the fallbacks lazily.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
parent f3a6f976
......@@ -9,7 +9,6 @@ related:
- app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag
- app/api-reference/functions/redirect
- app/api-reference/functions/unauthorized
---
You can mutate data in Next.js using [React Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions. For Next.js-specific behaviors (single-roundtrip response, sequential dispatch, security, deployment), see [Server Actions and Mutations](/docs/app/guides/server-actions).
......@@ -38,17 +37,14 @@ Behind the scenes, actions use the `POST` method, and only this HTTP method can
A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file.
The following example calls [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) fallback.
```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const title = formData.get('title')
......@@ -62,7 +58,7 @@ export async function deletePost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const id = formData.get('id')
......@@ -75,13 +71,12 @@ export async function deletePost(formData: FormData) {
```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const title = formData.get('title')
......@@ -95,7 +90,7 @@ export async function deletePost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const id = formData.get('id')
......@@ -249,12 +244,11 @@ export function Form() {
'use server'
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const title = formData.get('title')
......@@ -269,12 +263,11 @@ export async function createPost(formData: FormData) {
'use server'
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const title = formData.get('title')
......@@ -394,12 +387,11 @@ After a mutation, you may want to refresh the current page to show the latest da
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData: FormData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......@@ -413,12 +405,11 @@ export async function updatePost(formData: FormData) {
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......@@ -436,13 +427,12 @@ After performing a mutation, you can revalidate the Next.js cache and show the u
```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......@@ -454,13 +444,12 @@ export async function createPost(formData: FormData) {
```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......@@ -477,12 +466,12 @@ You may want to redirect the user to a different page after a mutation. You can
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect, unauthorized } from 'next/navigation'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......@@ -497,12 +486,12 @@ export async function createPost(formData: FormData) {
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect, unauthorized } from 'next/navigation'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
// Mutate data
// ...
......
......@@ -10,10 +10,6 @@ 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.
......@@ -155,23 +151,14 @@ 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'
type Props = {
export default async function Page({
params,
}: {
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)
......@@ -184,19 +171,10 @@ async function Post({ params }: Props) {
```
```jsx filename="app/blog/[slug]/page.js" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getPostBySlug } from '@/lib/posts'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<Post params={params} />
</Suspense>
)
}
async function Post({ params }) {
export default async function Page({ params }) {
const { slug } = await params
const post = getPostBySlug(slug)
......@@ -208,8 +186,6 @@ async function Post({ 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>
......@@ -222,116 +198,6 @@ 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.
......
......@@ -81,3 +81,15 @@ yarn add next@canary
```bash package="bun"
bun add next@canary
```
### Features available in canary
The following features are currently available in canary:
**Authentication**:
- [`forbidden`](/docs/app/api-reference/functions/forbidden)
- [`unauthorized`](/docs/app/api-reference/functions/unauthorized)
- [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden)
- [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized)
- [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts)
......@@ -338,29 +338,23 @@ export default async function Page() {
A page-level authentication check does not extend to the Server Actions defined within it. Always re-verify inside the action:
```tsx filename="app/admin/page.tsx" highlight={16,17,18,19,20,21,22,23}
```tsx filename="app/admin/page.tsx" highlight={13,14,15,16}
import { auth } from '@/lib/auth'
import { forbidden, redirect, unauthorized } from 'next/navigation'
import { redirect } from 'next/navigation'
export default async function AdminPage() {
const session = await auth()
if (!session?.user) {
if (!session?.user?.isAdmin) {
redirect('/login')
}
if (!session.user.isAdmin) {
forbidden()
}
return (
<form
action={async () => {
'use server'
const session = await auth()
if (!session?.user) {
unauthorized()
}
if (!session.user.isAdmin) {
forbidden()
if (!session?.user?.isAdmin) {
throw new Error('Unauthorized')
}
await db.record.deleteMany()
}}
......@@ -371,30 +365,27 @@ export default async function AdminPage() {
}
```
The page redirects unauthenticated visitors to sign in. The highlighted checks inside the action are still required because a Server Action is a separate entry point that may be called directly.
The highlighted `auth()` check inside the action is critical. The page-level redirect on line 6 controls which UI is rendered, but the Server Action is a separate entry point and must verify the caller on its own.
Beyond authentication (is the user logged in?), remember to check **authorization** (does this user have permission to act on this specific resource?). This prevents [Insecure Direct Object Reference (IDOR)](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html) vulnerabilities:
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Call [`forbidden()`](/docs/app/api-reference/functions/forbidden) when the user is authenticated but lacks permission. Next.js renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) or [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden) fallback.
```tsx filename="app/actions.ts"
'use server'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
// Check that the user owns this resource
if (post.authorId !== session.user.id) {
forbidden()
throw new Error('Forbidden')
}
await db.post.delete({ where: { id: postId } })
......@@ -412,18 +403,17 @@ import 'server-only'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
if (post.authorId !== session.user.id) {
forbidden()
throw new Error('Forbidden')
}
await db.post.delete({ where: { id: postId } })
......@@ -455,14 +445,13 @@ Server Action return values are serialized and sent to the client. Only return w
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { unauthorized } from 'next/navigation'
// BAD: Returns the full database record, which may include
// internal fields the client should not see.
export async function updateUser(data: FormData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
return db.user.update({
where: { id: session.user.id },
......@@ -474,7 +463,7 @@ export async function updateUser(data: FormData) {
export async function updateUserSafe(data: FormData) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
await db.user.update({
where: { id: session.user.id },
......
......@@ -9,8 +9,6 @@ React Server Actions are [Server Functions](https://react.dev/reference/rsc/serv
> [!WARNING]
> Always verify [authentication and authorization](/docs/app/guides/authentication) inside each Server Action, even if the form is only rendered on an authenticated page. See the [Data Security guide](/docs/app/guides/data-security) for more details.
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest `unauthorized.js` fallback.
## How it works
React extends the HTML [`<form>`](https://developer.mozilla.org/docs/Web/HTML/Element/form) element to allow Server Actions to be invoked with the [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form#action) attribute.
......@@ -19,7 +17,6 @@ When used in a form, the function automatically receives the [`FormData`](https:
```tsx filename="app/invoices/page.tsx" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() {
async function createInvoice(formData: FormData) {
......@@ -27,7 +24,7 @@ export default function Page() {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const rawFormData = {
......@@ -46,7 +43,6 @@ export default function Page() {
```jsx filename="app/invoices/page.js" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() {
async function createInvoice(formData) {
......@@ -54,7 +50,7 @@ export default function Page() {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const rawFormData = {
......
......@@ -51,13 +51,12 @@ A re-render is included in the same response when the action does any of these:
'use server'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) unauthorized()
if (!session?.user) throw new Error('Unauthorized')
await db.post.create({
data: {
......@@ -95,22 +94,21 @@ For end-to-end patterns including a Data Access Layer, return-value tainting, an
Destructive operations like deletes may warrant stronger handling, such as elevated session checks or re-authentication, and a loud failure when those checks miss.
```ts filename="app/posts/actions.ts" highlight={4,7,8,9}
```ts filename="app/posts/actions.ts" highlight={6,7,8}
'use server'
import { auth } from '@/lib/auth'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) unauthorized()
if (!(await canDelete(session.user, postId))) forbidden()
if (!session?.user) throw new Error('Unauthorized')
if (!(await canDelete(session.user, postId))) throw new Error('Forbidden')
await db.post.delete({ where: { id: postId } })
}
```
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when the request is not authenticated. Call [`forbidden()`](/docs/app/api-reference/functions/forbidden) when the user is authenticated but lacks permission. Next.js renders the corresponding `unauthorized.tsx` or `forbidden.tsx` fallback.
If you've enabled the experimental [`authInterrupts`](/docs/app/api-reference/config/next-config-js/authInterrupts) flag, you can throw [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) and [`forbidden()`](/docs/app/api-reference/functions/forbidden) from `next/navigation` instead, so Next.js renders the corresponding `unauthorized.tsx` / `forbidden.tsx` UI segment automatically.
For example, a client legitimately tells the server _which_ item to act on, but it should not supply the row's contents or ownership. Send a reference (typically an ID) plus the user's change, and re-read the rest from a trusted source using the session. Schema validation (zod or similar) only checks the _shape_ of the input. A well-formed `Item` object can still refer to a row the caller does not own.
......
......@@ -9,18 +9,17 @@ For Next.js-specific Server Action behaviors (response model, security, configur
## Using `use server` at the top of a file
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server. It calls [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated, which renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) fallback.
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server.
```tsx filename="app/actions.ts" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const user = await db.user.create({ data })
......@@ -32,12 +31,11 @@ export async function createUser(data: { name: string; email: string }) {
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const user = await db.user.create({ data })
......@@ -55,12 +53,11 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`:
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const users = await db.user.findMany({
......@@ -74,12 +71,11 @@ export async function fetchUsers() {
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const users = await db.user.findMany({
......@@ -161,36 +157,32 @@ Design your data access functions as secure primitives: validate inputs, check a
Always authenticate and authorize users before performing sensitive server-side operations. Read authentication from cookies or headers rather than accepting tokens as function parameters.
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest `unauthorized.js` fallback.
```tsx filename="app/actions.ts" highlight={1,5,8,9,10,11} switcher
```tsx filename="app/actions.ts" highlight={1,7,8,9,10} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name }
}
```
```jsx filename="app/actions.js" highlight={1,5,8,9,10,11} switcher
```jsx filename="app/actions.js" highlight={1,7,8,9,10} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data) {
const session = await auth()
if (!session?.user) {
unauthorized()
throw new Error('Unauthorized')
}
const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name }
......
......@@ -9,8 +9,6 @@ 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"
......
......@@ -4,14 +4,13 @@ description: API reference for the forbidden.js special file.
related:
links:
- app/api-reference/functions/forbidden
version: experimental
---
The **forbidden** file renders UI when the [`forbidden`](/docs/app/api-reference/functions/forbidden) function is invoked.
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'
......@@ -50,5 +49,4 @@ export default function Forbidden() {
| Version | Changes |
| --------- | -------------------------- |
| `v16.4.0` | `forbidden.js` is stable. |
| `v15.1.0` | `forbidden.js` introduced. |
......@@ -14,8 +14,6 @@ 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'
......
......@@ -4,14 +4,13 @@ description: API reference for the unauthorized.js special file.
related:
links:
- app/api-reference/functions/unauthorized
version: experimental
---
The **unauthorized** file renders UI when the [`unauthorized`](/docs/app/api-reference/functions/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](/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'
......@@ -114,5 +113,4 @@ export default function UnauthorizedPage() {
| Version | Changes |
| --------- | ----------------------------- |
| `v16.4.0` | `unauthorized.js` is stable. |
| `v15.1.0` | `unauthorized.js` introduced. |
---
title: forbidden
description: API Reference for the forbidden function.
version: experimental
related:
links:
- 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 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:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
module.exports = {
experimental: {
authInterrupts: true,
},
}
```
`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/admin/page.tsx" switcher
......@@ -256,7 +280,6 @@ export async function updateRole(formData) {
## Version History
| Version | Changes |
| --------- | ---------------------------------------------------------------------------------- |
| `v16.4.0` | `forbidden` is stable. The `experimental.authInterrupts` flag is no longer needed. |
| `v15.1.0` | `forbidden` introduced. |
| Version | Changes |
| --------- | ----------------------- |
| `v15.1.0` | `forbidden` introduced. |
---
title: unauthorized
description: API Reference for the unauthorized function.
version: experimental
related:
links:
- 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 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:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
module.exports = {
experimental: {
authInterrupts: true,
},
}
```
`unauthorized` 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/dashboard/page.tsx" switcher
......@@ -314,7 +338,6 @@ export async function GET() {
## Version History
| Version | Changes |
| --------- | ------------------------------------------------------------------------------------- |
| `v16.4.0` | `unauthorized` is stable. The `experimental.authInterrupts` flag is no longer needed. |
| `v15.1.0` | `unauthorized` introduced. |
| Version | Changes |
| --------- | -------------------------- |
| `v15.1.0` | `unauthorized` introduced. |
---
title: authInterrupts
description: Learn about the deprecated authInterrupts configuration option and how to update your configuration.
description: Learn how to enable the experimental `authInterrupts` configuration option to use `forbidden` and `unauthorized`.
version: canary
related:
links:
- app/api-reference/functions/forbidden
......@@ -9,8 +10,24 @@ related:
- app/api-reference/file-conventions/unauthorized
---
> **Deprecated**: `experimental.authInterrupts` is deprecated as of Next.js 16.4.0.
The `authInterrupts` configuration option allows you to use [`forbidden`](/docs/app/api-reference/functions/forbidden) and [`unauthorized`](/docs/app/api-reference/functions/unauthorized) APIs in your application. While these functions are experimental, you must enable the `authInterrupts` option in your `next.config.js` file to use them:
The [`forbidden()`](/docs/app/api-reference/functions/forbidden) and [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) APIs are now stable and available by default.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
Remove `experimental.authInterrupts` from your `next.config.js` or `next.config.ts` file. The option has no effect: setting it to either `true` or `false` does not change the availability of these APIs.
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
module.exports = {
experimental: {
authInterrupts: true,
},
}
```
/**
* Forbidden Auth
*
* Tests whether the agent uses the forbidden() function from next/navigation,
* plus a forbidden.tsx error boundary.
* Tests whether the agent uses the forbidden() function from next/navigation
* with authInterrupts enabled, plus a forbidden.tsx error boundary.
*
* Tricky because agents use redirect() or notFound() for authorization failures
* instead of the dedicated forbidden() API that returns a proper 403 status.
......@@ -12,6 +12,16 @@ import { expect, test } from 'vitest'
import { readFileSync, existsSync } from 'fs'
import { join } from 'path'
test('next.config enables authInterrupts', () => {
const configPath = join(process.cwd(), 'next.config.ts')
if (existsSync(configPath)) {
const content = readFileSync(configPath, 'utf-8')
// The forbidden() function requires authInterrupts: true
expect(content).toMatch(/authInterrupts\s*:\s*true/)
}
})
test('Admin page imports forbidden from next/navigation', () => {
const adminPagePath = join(process.cwd(), 'app', 'admin', 'page.tsx')
if (existsSync(adminPagePath)) {
......
......@@ -330,6 +330,8 @@ export function getDefineEnv({
'process.env.__NEXT_LINK_NO_TOUCH_START':
config.experimental.linkNoTouchStart ?? false,
'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,
'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':
!!config.experimental.authInterrupts,
'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(
process.env.NEXT_TELEMETRY_DISABLED
),
......
......@@ -1774,6 +1774,9 @@ export default async function build(
)
const isAppCacheComponentsEnabled = Boolean(config.cacheComponents)
const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts
)
const isAppPPREnabled = isAppCacheComponentsEnabled
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
......@@ -2393,6 +2396,7 @@ export default async function build(
configFileName,
cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout: config.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean(
config.experimental.durableUseCacheEntries
......@@ -2628,6 +2632,7 @@ export default async function build(
pageType,
cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout:
config.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean(
......
......@@ -868,6 +868,7 @@ export async function buildAppStaticPaths({
route,
distDir,
cacheComponents,
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
staticPageGenerationTimeout,
......@@ -892,6 +893,7 @@ export async function buildAppStaticPaths({
page: string
route: NormalizedAppRoute
cacheComponents: boolean
authInterrupts: boolean
useCacheTimeout: number
durableUseCacheEntries: boolean
staticPageGenerationTimeout: number
......@@ -968,6 +970,7 @@ export async function buildAppStaticPaths({
// TODO: remove validationLevel and other global config out of renderOpts
validationLevel: 'warning',
experimental: {
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
},
......
......@@ -1015,6 +1015,7 @@ export function createAppPageEntrypoint({
inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining:
nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout
),
......
......@@ -244,6 +244,7 @@ export async function handler(
previewProps,
renderOpts: {
experimental: {
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
useCacheTimeout: nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean(
nextConfig.experimental.durableUseCacheEntries
......
......@@ -58,6 +58,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
......
......@@ -194,6 +194,7 @@ async function requestHandler(
),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout
),
......@@ -462,6 +463,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
......
......@@ -407,6 +407,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
......
......@@ -123,6 +123,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
......
......@@ -50,6 +50,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
......
......@@ -795,6 +795,7 @@ export async function isPageStatic({
pageType,
cacheComponents,
partialPrefetching,
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
staticPageGenerationTimeout,
......@@ -815,6 +816,7 @@ export async function isPageStatic({
distDir: string
cacheComponents: boolean
partialPrefetching: boolean
authInterrupts: boolean
useCacheTimeout: number
durableUseCacheEntries: boolean
staticPageGenerationTimeout: number
......@@ -1011,6 +1013,7 @@ export async function isPageStatic({
page,
route,
cacheComponents,
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
staticPageGenerationTimeout,
......
......@@ -3,7 +3,9 @@ import {
type HTTPAccessFallbackError,
} from './http-access-fallback/http-access-fallback'
// TODO: Add `forbidden` docs
/**
* @experimental
* This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)
* within a route segment as well as inject a tag.
*
......@@ -18,6 +20,12 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`
export function forbidden(): never {
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {
throw new Error(
`\`forbidden()\` is experimental and only allowed to be enabled when \`experimental.authInterrupts\` is enabled.`
)
}
const error = new Error(DIGEST) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST
throw error
......
......@@ -3,7 +3,9 @@ import {
type HTTPAccessFallbackError,
} from './http-access-fallback/http-access-fallback'
// TODO: Add `unauthorized` docs
/**
* @experimental
* This function allows you to render the [unauthorized.js file](https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized)
* within a route segment as well as inject a tag.
*
......@@ -19,6 +21,12 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`
export function unauthorized(): never {
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {
throw new Error(
`\`unauthorized()\` is experimental and only allowed to be used when \`experimental.authInterrupts\` is enabled.`
)
}
const error = new Error(DIGEST) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST
throw error
......
......@@ -518,6 +518,7 @@ async function exportAppImpl(
nextConfig.experimental.parallelRouteMetadata ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
reactBrowserBailout: nextConfig.experimental.reactBrowserBailout ?? false,
useCacheTimeout: nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean(
......
......@@ -47,7 +47,10 @@ export async function exportAppRoute(
cacheComponents: boolean,
staticPageGenerationTimeout: number,
experimental: Required<
Pick<ExperimentalConfig, 'useCacheTimeout' | 'durableUseCacheEntries'>
Pick<
ExperimentalConfig,
'authInterrupts' | 'useCacheTimeout' | 'durableUseCacheEntries'
>
>,
buildId: string,
deploymentId: string,
......
......@@ -2131,6 +2131,7 @@ async function getRSCPayload(
rootLayoutIncluded: false,
missingSlots,
preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataOutlet,
isPrerendering,
hintTree: hints,
......
......@@ -68,6 +68,7 @@ type CreateComponentTreeProps = {
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType<{ tree: LoaderTree }>
isPrerendering: boolean
hintTree: PrefetchHints | null
......@@ -133,6 +134,7 @@ async function createComponentTreeInternal(
ctx,
missingSlots,
preloadCallbacks,
authInterrupts,
MetadataOutlet,
isPrerendering,
hintTree,
......@@ -147,6 +149,7 @@ async function createComponentTreeInternal(
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType<{ tree: LoaderTree }> | null
isPrerendering: boolean
hintTree: PrefetchHints | null
......@@ -276,25 +279,27 @@ async function createComponentTreeInternal(
})
: []
const [Forbidden, forbiddenStyles] = forbidden
? await createComponentStylesAndScripts({
ctx,
filePath: forbidden[1],
getComponent: forbidden[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
? await createComponentStylesAndScripts({
ctx,
filePath: forbidden[1],
getComponent: forbidden[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
const [Unauthorized, unauthorizedStyles] = unauthorized
? await createComponentStylesAndScripts({
ctx,
filePath: unauthorized[1],
getComponent: unauthorized[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
const [Unauthorized, unauthorizedStyles] =
authInterrupts && unauthorized
? await createComponentStylesAndScripts({
ctx,
filePath: unauthorized[1],
getComponent: unauthorized[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
let dynamic = layoutOrPageMod?.dynamic
......@@ -617,6 +622,7 @@ async function createComponentTreeInternal(
ctx,
missingSlots,
preloadCallbacks,
authInterrupts,
MetadataOutlet:
experimental.parallelRouteMetadata || isChildrenRouteKey
? MetadataOutlet
......
......@@ -171,6 +171,7 @@ export interface RenderOptsPartial {
parallelRouteMetadata: boolean
inlineCss: boolean
prefetchInlining: PrefetchInliningConfig
authInterrupts: boolean
reactBrowserBailout: boolean
serverComponentsHmrCancellation?: boolean
useCacheTimeout: number
......
......@@ -266,6 +266,7 @@ export async function walkTreeWithFlightRouterState({
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet,
isPrerendering: false,
hintTree,
......@@ -396,7 +397,10 @@ export async function createFullTreeForNavigation({
preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType<{ tree: LoaderTree }>
}): Promise<NavigationResponseTree> {
const { pagePath } = ctx
const {
renderOpts: { experimental },
pagePath,
} = ctx
const hintTreeForInitialRender =
ctx.renderOpts.prefetchHints?.[pagePath] ?? null
......@@ -412,6 +416,7 @@ export async function createFullTreeForNavigation({
injectedFontPreloadTags,
rootLayoutIncluded: false,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet,
isPrerendering: false,
hintTree: hintTreeForInitialRender,
......
......@@ -41,7 +41,10 @@ export type WorkStoreContext = {
pendingWaitUntil?: Promise<any>
experimental: Pick<
RenderOpts['experimental'],
'isRoutePPREnabled' | 'useCacheTimeout' | 'durableUseCacheEntries'
| 'isRoutePPREnabled'
| 'authInterrupts'
| 'useCacheTimeout'
| 'durableUseCacheEntries'
>
/**
......
......@@ -627,6 +627,7 @@ export default abstract class Server<
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
prefetchInlining:
this.nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
reactBrowserBailout:
this.nextConfig.experimental.reactBrowserBailout ?? false,
serverComponentsHmrCancellation:
......
......@@ -1462,9 +1462,9 @@ export interface ExperimentalConfig {
*/
inlineCss?: boolean
// TODO: Remove this config when the API is stable.
/**
* @deprecated `forbidden()` and `unauthorized()` are available by default.
* This option has no effect and can be removed.
* This config allows you to enable the experimental navigation API `forbidden` and `unauthorized`.
*/
authInterrupts?: boolean
......@@ -2456,6 +2456,7 @@ export const defaultConfig = Object.freeze({
parallelServerCompiles: false,
parallelServerBuildTraces: false,
ppr: false,
authInterrupts: false,
webpackBuildWorker: undefined,
webpackMemoryOptimizations: false,
optimizeServerReact: true,
......@@ -2575,6 +2576,7 @@ export interface NextConfigRuntime {
| 'parallelRouteMetadata'
| 'inlineCss'
| 'prefetchInlining'
| 'authInterrupts'
| 'reactBrowserBailout'
| 'useCacheTimeout'
| 'durableUseCacheEntries'
......@@ -2646,6 +2648,7 @@ export function getNextConfigRuntime(
parallelRouteMetadata: ex.parallelRouteMetadata,
inlineCss: ex.inlineCss,
prefetchInlining: ex.prefetchInlining,
authInterrupts: ex.authInterrupts,
reactBrowserBailout: ex.reactBrowserBailout,
useCacheTimeout: ex.useCacheTimeout,
durableUseCacheEntries: ex.durableUseCacheEntries,
......
......@@ -245,13 +245,6 @@ function checkDeprecations(
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'experimental.authInterrupts',
`\`experimental.authInterrupts\` is no longer needed, because \`forbidden\` and \`unauthorized\` are available by default. You can remove it from ${configFileName}.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'eslint',
......
......@@ -766,6 +766,7 @@ export default class DevServer extends Server {
nextConfigOutput: this.nextConfig.output,
buildId: this.buildId,
deploymentId: this.deploymentId,
authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),
useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean(
this.nextConfig.experimental.durableUseCacheEntries
......
......@@ -53,6 +53,7 @@ export async function loadStaticPaths({
nextConfigOutput,
buildId,
deploymentId,
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
staticPageGenerationTimeout,
......@@ -77,6 +78,7 @@ export async function loadStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string
deploymentId: string
authInterrupts: boolean
useCacheTimeout: number
durableUseCacheEntries: boolean
staticPageGenerationTimeout: number
......@@ -159,6 +161,7 @@ export async function loadStaticPaths({
isEnsureStaticPage,
buildId,
deploymentId,
authInterrupts,
useCacheTimeout,
durableUseCacheEntries,
staticPageGenerationTimeout,
......
......@@ -334,6 +334,8 @@ export async function adapter(
validationLevel: 'warning',
experimental: {
isRoutePPREnabled: false,
authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts,
// Proxy doesn't fill Cache Components entries, so this value
// is never read. 0 is a sentinel: if something ever reads it,
// the cache fill will time out immediately and surface the
......
......@@ -127,6 +127,7 @@ export class EdgeRouteModuleWrapper {
// TODO: Remove validationLevel and other global config from renderOpts
validationLevel: 'warning',
experimental: {
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,
// Edge runtime doesn't support Cache Components, so this value is
// never read. 0 is a sentinel: if something ever reads it, the cache
// fill will time out immediately and surface the bug.
......
......@@ -23,7 +23,7 @@ export interface RequestData {
trailingSlash?: boolean
experimental?: Pick<
ExperimentalConfig,
'cacheLife' | 'clientParamParsingOrigins'
'cacheLife' | 'authInterrupts' | 'clientParamParsingOrigins'
>
}
page?: {
......
......@@ -3,6 +3,7 @@
*/
const nextConfig = {
experimental: {
authInterrupts: true,
globalNotFound: true,
},
}
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
......@@ -4,6 +4,7 @@
const nextConfig = {
cacheComponents: true,
experimental: {
authInterrupts: true,
instantInsights: {
validationLevel: 'manual-warning',
},
......
......@@ -3,6 +3,7 @@
*/
const nextConfig = {
experimental: {
authInterrupts: true,
explicitParallelRouteChildren: true,
},
}
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
authInterrupts: true,
},
}
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