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: ...@@ -9,7 +9,6 @@ related:
- app/api-reference/functions/revalidatePath - app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag - app/api-reference/functions/revalidateTag
- app/api-reference/functions/redirect - 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). 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 ...@@ -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. 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 ```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const title = formData.get('title') const title = formData.get('title')
...@@ -62,7 +58,7 @@ export async function deletePost(formData: FormData) { ...@@ -62,7 +58,7 @@ export async function deletePost(formData: FormData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const id = formData.get('id') const id = formData.get('id')
...@@ -75,13 +71,12 @@ export async function deletePost(formData: FormData) { ...@@ -75,13 +71,12 @@ export async function deletePost(formData: FormData) {
```js filename="app/lib/actions.js" switcher ```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const title = formData.get('title') const title = formData.get('title')
...@@ -95,7 +90,7 @@ export async function deletePost(formData) { ...@@ -95,7 +90,7 @@ export async function deletePost(formData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const id = formData.get('id') const id = formData.get('id')
...@@ -249,12 +244,11 @@ export function Form() { ...@@ -249,12 +244,11 @@ export function Form() {
'use server' 'use server'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const title = formData.get('title') const title = formData.get('title')
...@@ -269,12 +263,11 @@ export async function createPost(formData: FormData) { ...@@ -269,12 +263,11 @@ export async function createPost(formData: FormData) {
'use server' 'use server'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const title = formData.get('title') 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 ...@@ -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 { auth } from '@/lib/auth'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData: FormData) { export async function updatePost(formData: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
...@@ -413,12 +405,11 @@ export async function updatePost(formData: FormData) { ...@@ -413,12 +405,11 @@ export async function updatePost(formData: FormData) {
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData) { export async function updatePost(formData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
...@@ -436,13 +427,12 @@ After performing a mutation, you can revalidate the Next.js cache and show the u ...@@ -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 ```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
...@@ -454,13 +444,12 @@ export async function createPost(formData: FormData) { ...@@ -454,13 +444,12 @@ export async function createPost(formData: FormData) {
```js filename="app/lib/actions.js" switcher ```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
...@@ -477,12 +466,12 @@ You may want to redirect the user to a different page after a mutation. You can ...@@ -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 { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { redirect, unauthorized } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
...@@ -497,12 +486,12 @@ export async function createPost(formData: FormData) { ...@@ -497,12 +486,12 @@ export async function createPost(formData: FormData) {
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { redirect, unauthorized } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
// Mutate data // Mutate data
// ... // ...
......
...@@ -10,10 +10,6 @@ related: ...@@ -10,10 +10,6 @@ related:
- app/api-reference/functions/catchError - app/api-reference/functions/catchError
- app/api-reference/functions/not-found - app/api-reference/functions/not-found
- app/api-reference/file-conventions/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. 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() { ...@@ -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. 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 ```tsx filename="app/blog/[slug]/page.tsx" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
import { getPostBySlug } from '@/lib/posts' import { getPostBySlug } from '@/lib/posts'
type Props = { export default async function Page({
params,
}: {
params: Promise<{ slug: string }> 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 { slug } = await params
const post = getPostBySlug(slug) const post = getPostBySlug(slug)
...@@ -184,19 +171,10 @@ async function Post({ params }: Props) { ...@@ -184,19 +171,10 @@ async function Post({ params }: Props) {
``` ```
```jsx filename="app/blog/[slug]/page.js" switcher ```jsx filename="app/blog/[slug]/page.js" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
import { getPostBySlug } from '@/lib/posts' import { getPostBySlug } from '@/lib/posts'
export default function Page({ params }) { export default async function Page({ params }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<Post params={params} />
</Suspense>
)
}
async function Post({ params }) {
const { slug } = await params const { slug } = await params
const post = getPostBySlug(slug) const post = getPostBySlug(slug)
...@@ -208,8 +186,6 @@ async function Post({ params }) { ...@@ -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 ```tsx filename="app/blog/[slug]/not-found.tsx" switcher
export default function NotFound() { export default function NotFound() {
return <div>404 - Page Not Found</div> return <div>404 - Page Not Found</div>
...@@ -222,116 +198,6 @@ export default function NotFound() { ...@@ -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 ## 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. 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 ...@@ -81,3 +81,15 @@ yarn add next@canary
```bash package="bun" ```bash package="bun"
bun add next@canary 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() { ...@@ -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: 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 { auth } from '@/lib/auth'
import { forbidden, redirect, unauthorized } from 'next/navigation' import { redirect } from 'next/navigation'
export default async function AdminPage() { export default async function AdminPage() {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user?.isAdmin) {
redirect('/login') redirect('/login')
} }
if (!session.user.isAdmin) {
forbidden()
}
return ( return (
<form <form
action={async () => { action={async () => {
'use server' 'use server'
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user?.isAdmin) {
unauthorized() throw new Error('Unauthorized')
}
if (!session.user.isAdmin) {
forbidden()
} }
await db.record.deleteMany() await db.record.deleteMany()
}} }}
...@@ -371,30 +365,27 @@ export default async function AdminPage() { ...@@ -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: 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" ```tsx filename="app/actions.ts"
'use server' 'use server'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { db } from '@/lib/db' import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) { export async function deletePost(postId: string) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const post = await db.post.findUnique({ where: { id: postId } }) const post = await db.post.findUnique({ where: { id: postId } })
// Check that the user owns this resource // Check that the user owns this resource
if (post.authorId !== session.user.id) { if (post.authorId !== session.user.id) {
forbidden() throw new Error('Forbidden')
} }
await db.post.delete({ where: { id: postId } }) await db.post.delete({ where: { id: postId } })
...@@ -412,18 +403,17 @@ import 'server-only' ...@@ -412,18 +403,17 @@ import 'server-only'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { db } from '@/lib/db' import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) { export async function deletePost(postId: string) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const post = await db.post.findUnique({ where: { id: postId } }) const post = await db.post.findUnique({ where: { id: postId } })
if (post.authorId !== session.user.id) { if (post.authorId !== session.user.id) {
forbidden() throw new Error('Forbidden')
} }
await db.post.delete({ where: { id: postId } }) 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 ...@@ -455,14 +445,13 @@ Server Action return values are serialized and sent to the client. Only return w
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { db } from '@/lib/db' import { db } from '@/lib/db'
import { unauthorized } from 'next/navigation'
// BAD: Returns the full database record, which may include // BAD: Returns the full database record, which may include
// internal fields the client should not see. // internal fields the client should not see.
export async function updateUser(data: FormData) { export async function updateUser(data: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
return db.user.update({ return db.user.update({
where: { id: session.user.id }, where: { id: session.user.id },
...@@ -474,7 +463,7 @@ export async function updateUser(data: FormData) { ...@@ -474,7 +463,7 @@ export async function updateUser(data: FormData) {
export async function updateUserSafe(data: FormData) { export async function updateUserSafe(data: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
await db.user.update({ await db.user.update({
where: { id: session.user.id }, where: { id: session.user.id },
......
...@@ -9,8 +9,6 @@ React Server Actions are [Server Functions](https://react.dev/reference/rsc/serv ...@@ -9,8 +9,6 @@ React Server Actions are [Server Functions](https://react.dev/reference/rsc/serv
> [!WARNING] > [!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. > 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 ## 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. 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: ...@@ -19,7 +17,6 @@ When used in a form, the function automatically receives the [`FormData`](https:
```tsx filename="app/invoices/page.tsx" switcher ```tsx filename="app/invoices/page.tsx" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() { export default function Page() {
async function createInvoice(formData: FormData) { async function createInvoice(formData: FormData) {
...@@ -27,7 +24,7 @@ export default function Page() { ...@@ -27,7 +24,7 @@ export default function Page() {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const rawFormData = { const rawFormData = {
...@@ -46,7 +43,6 @@ export default function Page() { ...@@ -46,7 +43,6 @@ export default function Page() {
```jsx filename="app/invoices/page.js" switcher ```jsx filename="app/invoices/page.js" switcher
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() { export default function Page() {
async function createInvoice(formData) { async function createInvoice(formData) {
...@@ -54,7 +50,7 @@ export default function Page() { ...@@ -54,7 +50,7 @@ export default function Page() {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const rawFormData = { const rawFormData = {
......
...@@ -51,13 +51,12 @@ A re-render is included in the same response when the action does any of these: ...@@ -51,13 +51,12 @@ A re-render is included in the same response when the action does any of these:
'use server' 'use server'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { db } from '@/lib/db' import { db } from '@/lib/db'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const session = await auth() const session = await auth()
if (!session?.user) unauthorized() if (!session?.user) throw new Error('Unauthorized')
await db.post.create({ await db.post.create({
data: { data: {
...@@ -95,22 +94,21 @@ For end-to-end patterns including a Data Access Layer, return-value tainting, an ...@@ -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. 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' 'use server'
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) { export async function deletePost(postId: string) {
const session = await auth() const session = await auth()
if (!session?.user) unauthorized() if (!session?.user) throw new Error('Unauthorized')
if (!(await canDelete(session.user, postId))) forbidden() if (!(await canDelete(session.user, postId))) throw new Error('Forbidden')
await db.post.delete({ where: { id: postId } }) 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. 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 ...@@ -9,18 +9,17 @@ For Next.js-specific Server Action behaviors (response model, security, configur
## Using `use server` at the top of a file ## 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 ```tsx filename="app/actions.ts" highlight={1} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) { export async function createUser(data: { name: string; email: string }) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const user = await db.user.create({ data }) const user = await db.user.create({ data })
...@@ -32,12 +31,11 @@ export async function createUser(data: { name: string; email: string }) { ...@@ -32,12 +31,11 @@ export async function createUser(data: { name: string; email: string }) {
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data) { export async function createUser(data) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const user = await db.user.create({ data }) const user = await db.user.create({ data })
...@@ -55,12 +53,11 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`: ...@@ -55,12 +53,11 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`:
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() { export async function fetchUsers() {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const users = await db.user.findMany({ const users = await db.user.findMany({
...@@ -74,12 +71,11 @@ export async function fetchUsers() { ...@@ -74,12 +71,11 @@ export async function fetchUsers() {
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() { export async function fetchUsers() {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const users = await db.user.findMany({ const users = await db.user.findMany({
...@@ -161,36 +157,32 @@ Design your data access functions as secure primitives: validate inputs, check a ...@@ -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. 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,7,8,9,10} switcher
```tsx filename="app/actions.ts" highlight={1,5,8,9,10,11} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) { export async function createUser(data: { name: string; email: string }) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const newUser = await db.user.create({ data }) const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name } 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' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data) { export async function createUser(data) {
const session = await auth() const session = await auth()
if (!session?.user) { if (!session?.user) {
unauthorized() throw new Error('Unauthorized')
} }
const newUser = await db.user.create({ data }) const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name } return { id: newUser.id, name: newUser.name }
......
...@@ -9,8 +9,6 @@ related: ...@@ -9,8 +9,6 @@ related:
An **error** file allows you to handle unexpected runtime errors and display fallback UI. 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 <Image
alt="error.js special file" alt="error.js special file"
srcLight="/docs/light/error-special-file.png" srcLight="/docs/light/error-special-file.png"
......
...@@ -4,14 +4,13 @@ description: API reference for the forbidden.js special file. ...@@ -4,14 +4,13 @@ description: API reference for the forbidden.js special file.
related: related:
links: links:
- app/api-reference/functions/forbidden - app/api-reference/functions/forbidden
version: experimental
--- ---
The **forbidden** file renders UI when the [`forbidden`](/docs/app/api-reference/functions/forbidden) function is invoked. 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. 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 ```tsx filename="app/forbidden.tsx" switcher
import Link from 'next/link' import Link from 'next/link'
...@@ -50,5 +49,4 @@ export default function Forbidden() { ...@@ -50,5 +49,4 @@ export default function Forbidden() {
| Version | Changes | | Version | Changes |
| --------- | -------------------------- | | --------- | -------------------------- |
| `v16.4.0` | `forbidden.js` is stable. |
| `v15.1.0` | `forbidden.js` introduced. | | `v15.1.0` | `forbidden.js` introduced. |
...@@ -14,8 +14,6 @@ The **not-found** file renders UI when the [`notFound`](/docs/app/api-reference/ ...@@ -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. 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 ```tsx filename="app/not-found.tsx" switcher
import Link from 'next/link' import Link from 'next/link'
......
...@@ -4,14 +4,13 @@ description: API reference for the unauthorized.js special file. ...@@ -4,14 +4,13 @@ description: API reference for the unauthorized.js special file.
related: related:
links: links:
- app/api-reference/functions/unauthorized - app/api-reference/functions/unauthorized
version: experimental
--- ---
The **unauthorized** file renders UI when the [`unauthorized`](/docs/app/api-reference/functions/unauthorized) function is invoked. 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. 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 ```tsx filename="app/unauthorized.tsx" switcher
import Login from '@/app/components/Login' import Login from '@/app/components/Login'
...@@ -114,5 +113,4 @@ export default function UnauthorizedPage() { ...@@ -114,5 +113,4 @@ export default function UnauthorizedPage() {
| Version | Changes | | Version | Changes |
| --------- | ----------------------------- | | --------- | ----------------------------- |
| `v16.4.0` | `unauthorized.js` is stable. |
| `v15.1.0` | `unauthorized.js` introduced. | | `v15.1.0` | `unauthorized.js` introduced. |
--- ---
title: forbidden title: forbidden
description: API Reference for the forbidden function. description: API Reference for the forbidden function.
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/not-found
- app/api-reference/functions/unauthorized - 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). 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. 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). `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 ```tsx filename="app/admin/page.tsx" switcher
...@@ -256,7 +280,6 @@ export async function updateRole(formData) { ...@@ -256,7 +280,6 @@ export async function updateRole(formData) {
## Version History ## Version History
| Version | Changes | | Version | Changes |
| --------- | ---------------------------------------------------------------------------------- | | --------- | ----------------------- |
| `v16.4.0` | `forbidden` is stable. The `experimental.authInterrupts` flag is no longer needed. | | `v15.1.0` | `forbidden` introduced. |
| `v15.1.0` | `forbidden` introduced. |
--- ---
title: unauthorized title: unauthorized
description: API Reference for the unauthorized function. description: API Reference for the unauthorized function.
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/not-found
- app/api-reference/functions/forbidden - 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). 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. 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). `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 ```tsx filename="app/dashboard/page.tsx" switcher
...@@ -314,7 +338,6 @@ export async function GET() { ...@@ -314,7 +338,6 @@ export async function GET() {
## Version History ## Version History
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------- | | --------- | -------------------------- |
| `v16.4.0` | `unauthorized` is stable. The `experimental.authInterrupts` flag is no longer needed. | | `v15.1.0` | `unauthorized` introduced. |
| `v15.1.0` | `unauthorized` introduced. |
--- ---
title: authInterrupts 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: related:
links: links:
- app/api-reference/functions/forbidden - app/api-reference/functions/forbidden
...@@ -9,8 +10,24 @@ related: ...@@ -9,8 +10,24 @@ related:
- app/api-reference/file-conventions/unauthorized - 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 * Forbidden Auth
* *
* Tests whether the agent uses the forbidden() function from next/navigation, * Tests whether the agent uses the forbidden() function from next/navigation
* plus a forbidden.tsx error boundary. * with authInterrupts enabled, plus a forbidden.tsx error boundary.
* *
* Tricky because agents use redirect() or notFound() for authorization failures * Tricky because agents use redirect() or notFound() for authorization failures
* instead of the dedicated forbidden() API that returns a proper 403 status. * instead of the dedicated forbidden() API that returns a proper 403 status.
...@@ -12,6 +12,16 @@ import { expect, test } from 'vitest' ...@@ -12,6 +12,16 @@ import { expect, test } from 'vitest'
import { readFileSync, existsSync } from 'fs' import { readFileSync, existsSync } from 'fs'
import { join } from 'path' 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', () => { test('Admin page imports forbidden from next/navigation', () => {
const adminPagePath = join(process.cwd(), 'app', 'admin', 'page.tsx') const adminPagePath = join(process.cwd(), 'app', 'admin', 'page.tsx')
if (existsSync(adminPagePath)) { if (existsSync(adminPagePath)) {
......
...@@ -330,6 +330,8 @@ export function getDefineEnv({ ...@@ -330,6 +330,8 @@ export function getDefineEnv({
'process.env.__NEXT_LINK_NO_TOUCH_START': 'process.env.__NEXT_LINK_NO_TOUCH_START':
config.experimental.linkNoTouchStart ?? false, config.experimental.linkNoTouchStart ?? false,
'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix, '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': Boolean(
process.env.NEXT_TELEMETRY_DISABLED process.env.NEXT_TELEMETRY_DISABLED
), ),
......
...@@ -1774,6 +1774,9 @@ export default async function build( ...@@ -1774,6 +1774,9 @@ export default async function build(
) )
const isAppCacheComponentsEnabled = Boolean(config.cacheComponents) const isAppCacheComponentsEnabled = Boolean(config.cacheComponents)
const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts
)
const isAppPPREnabled = isAppCacheComponentsEnabled const isAppPPREnabled = isAppCacheComponentsEnabled
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
...@@ -2393,6 +2396,7 @@ export default async function build( ...@@ -2393,6 +2396,7 @@ export default async function build(
configFileName, configFileName,
cacheComponents: isAppCacheComponentsEnabled, cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching, partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout: config.experimental.useCacheTimeout, useCacheTimeout: config.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
config.experimental.durableUseCacheEntries config.experimental.durableUseCacheEntries
...@@ -2628,6 +2632,7 @@ export default async function build( ...@@ -2628,6 +2632,7 @@ export default async function build(
pageType, pageType,
cacheComponents: isAppCacheComponentsEnabled, cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching, partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout: useCacheTimeout:
config.experimental.useCacheTimeout, config.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
......
...@@ -868,6 +868,7 @@ export async function buildAppStaticPaths({ ...@@ -868,6 +868,7 @@ export async function buildAppStaticPaths({
route, route,
distDir, distDir,
cacheComponents, cacheComponents,
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
...@@ -892,6 +893,7 @@ export async function buildAppStaticPaths({ ...@@ -892,6 +893,7 @@ export async function buildAppStaticPaths({
page: string page: string
route: NormalizedAppRoute route: NormalizedAppRoute
cacheComponents: boolean cacheComponents: boolean
authInterrupts: boolean
useCacheTimeout: number useCacheTimeout: number
durableUseCacheEntries: boolean durableUseCacheEntries: boolean
staticPageGenerationTimeout: number staticPageGenerationTimeout: number
...@@ -968,6 +970,7 @@ export async function buildAppStaticPaths({ ...@@ -968,6 +970,7 @@ export async function buildAppStaticPaths({
// TODO: remove validationLevel and other global config out of renderOpts // TODO: remove validationLevel and other global config out of renderOpts
validationLevel: 'warning', validationLevel: 'warning',
experimental: { experimental: {
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
}, },
......
...@@ -1015,6 +1015,7 @@ export function createAppPageEntrypoint({ ...@@ -1015,6 +1015,7 @@ export function createAppPageEntrypoint({
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: prefetchInlining:
nextConfig.experimental.prefetchInlining ?? false, nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean( reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout nextConfig.experimental.reactBrowserBailout
), ),
......
...@@ -244,6 +244,7 @@ export async function handler( ...@@ -244,6 +244,7 @@ export async function handler(
previewProps, previewProps,
renderOpts: { renderOpts: {
experimental: { experimental: {
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
useCacheTimeout: nextConfig.experimental.useCacheTimeout, useCacheTimeout: nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
nextConfig.experimental.durableUseCacheEntries nextConfig.experimental.durableUseCacheEntries
......
...@@ -58,6 +58,9 @@ export async function handler( ...@@ -58,6 +58,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: { experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any, cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
}, },
......
...@@ -194,6 +194,7 @@ async function requestHandler( ...@@ -194,6 +194,7 @@ async function requestHandler(
), ),
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false, prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean( reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout nextConfig.experimental.reactBrowserBailout
), ),
...@@ -462,6 +463,9 @@ export async function handler( ...@@ -462,6 +463,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: { experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any, cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
}, },
......
...@@ -407,6 +407,9 @@ export async function handler( ...@@ -407,6 +407,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: { experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any, cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
}, },
......
...@@ -123,6 +123,9 @@ export async function handler( ...@@ -123,6 +123,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: { experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any, cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
}, },
......
...@@ -50,6 +50,9 @@ export async function handler( ...@@ -50,6 +50,9 @@ export async function handler(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: { experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any, cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
}, },
......
...@@ -795,6 +795,7 @@ export async function isPageStatic({ ...@@ -795,6 +795,7 @@ export async function isPageStatic({
pageType, pageType,
cacheComponents, cacheComponents,
partialPrefetching, partialPrefetching,
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
...@@ -815,6 +816,7 @@ export async function isPageStatic({ ...@@ -815,6 +816,7 @@ export async function isPageStatic({
distDir: string distDir: string
cacheComponents: boolean cacheComponents: boolean
partialPrefetching: boolean partialPrefetching: boolean
authInterrupts: boolean
useCacheTimeout: number useCacheTimeout: number
durableUseCacheEntries: boolean durableUseCacheEntries: boolean
staticPageGenerationTimeout: number staticPageGenerationTimeout: number
...@@ -1011,6 +1013,7 @@ export async function isPageStatic({ ...@@ -1011,6 +1013,7 @@ export async function isPageStatic({
page, page,
route, route,
cacheComponents, cacheComponents,
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
......
...@@ -3,7 +3,9 @@ import { ...@@ -3,7 +3,9 @@ import {
type HTTPAccessFallbackError, type HTTPAccessFallbackError,
} from './http-access-fallback/http-access-fallback' } 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) * 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. * within a route segment as well as inject a tag.
* *
...@@ -18,6 +20,12 @@ import { ...@@ -18,6 +20,12 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403` const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`
export function forbidden(): never { 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 const error = new Error(DIGEST) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST ;(error as HTTPAccessFallbackError).digest = DIGEST
throw error throw error
......
...@@ -3,7 +3,9 @@ import { ...@@ -3,7 +3,9 @@ import {
type HTTPAccessFallbackError, type HTTPAccessFallbackError,
} from './http-access-fallback/http-access-fallback' } 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) * 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. * within a route segment as well as inject a tag.
* *
...@@ -19,6 +21,12 @@ import { ...@@ -19,6 +21,12 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401` const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`
export function unauthorized(): never { 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 const error = new Error(DIGEST) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST ;(error as HTTPAccessFallbackError).digest = DIGEST
throw error throw error
......
...@@ -518,6 +518,7 @@ async function exportAppImpl( ...@@ -518,6 +518,7 @@ async function exportAppImpl(
nextConfig.experimental.parallelRouteMetadata ?? false, nextConfig.experimental.parallelRouteMetadata ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false, inlineCss: nextConfig.experimental.inlineCss ?? false,
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false, prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
reactBrowserBailout: nextConfig.experimental.reactBrowserBailout ?? false, reactBrowserBailout: nextConfig.experimental.reactBrowserBailout ?? false,
useCacheTimeout: nextConfig.experimental.useCacheTimeout, useCacheTimeout: nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
......
...@@ -47,7 +47,10 @@ export async function exportAppRoute( ...@@ -47,7 +47,10 @@ export async function exportAppRoute(
cacheComponents: boolean, cacheComponents: boolean,
staticPageGenerationTimeout: number, staticPageGenerationTimeout: number,
experimental: Required< experimental: Required<
Pick<ExperimentalConfig, 'useCacheTimeout' | 'durableUseCacheEntries'> Pick<
ExperimentalConfig,
'authInterrupts' | 'useCacheTimeout' | 'durableUseCacheEntries'
>
>, >,
buildId: string, buildId: string,
deploymentId: string, deploymentId: string,
......
...@@ -2131,6 +2131,7 @@ async function getRSCPayload( ...@@ -2131,6 +2131,7 @@ async function getRSCPayload(
rootLayoutIncluded: false, rootLayoutIncluded: false,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataOutlet, MetadataOutlet,
isPrerendering, isPrerendering,
hintTree: hints, hintTree: hints,
......
...@@ -68,6 +68,7 @@ type CreateComponentTreeProps = { ...@@ -68,6 +68,7 @@ type CreateComponentTreeProps = {
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType<{ tree: LoaderTree }> MetadataOutlet: ComponentType<{ tree: LoaderTree }>
isPrerendering: boolean isPrerendering: boolean
hintTree: PrefetchHints | null hintTree: PrefetchHints | null
...@@ -133,6 +134,7 @@ async function createComponentTreeInternal( ...@@ -133,6 +134,7 @@ async function createComponentTreeInternal(
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts,
MetadataOutlet, MetadataOutlet,
isPrerendering, isPrerendering,
hintTree, hintTree,
...@@ -147,6 +149,7 @@ async function createComponentTreeInternal( ...@@ -147,6 +149,7 @@ async function createComponentTreeInternal(
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType<{ tree: LoaderTree }> | null MetadataOutlet: ComponentType<{ tree: LoaderTree }> | null
isPrerendering: boolean isPrerendering: boolean
hintTree: PrefetchHints | null hintTree: PrefetchHints | null
...@@ -276,25 +279,27 @@ async function createComponentTreeInternal( ...@@ -276,25 +279,27 @@ async function createComponentTreeInternal(
}) })
: [] : []
const [Forbidden, forbiddenStyles] = forbidden const [Forbidden, forbiddenStyles] =
? await createComponentStylesAndScripts({ authInterrupts && forbidden
ctx, ? await createComponentStylesAndScripts({
filePath: forbidden[1], ctx,
getComponent: forbidden[0], filePath: forbidden[1],
injectedCSS: injectedCSSWithCurrentLayout, getComponent: forbidden[0],
injectedJS: injectedJSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
}) injectedJS: injectedJSWithCurrentLayout,
: [] })
: []
const [Unauthorized, unauthorizedStyles] = unauthorized const [Unauthorized, unauthorizedStyles] =
? await createComponentStylesAndScripts({ authInterrupts && unauthorized
ctx, ? await createComponentStylesAndScripts({
filePath: unauthorized[1], ctx,
getComponent: unauthorized[0], filePath: unauthorized[1],
injectedCSS: injectedCSSWithCurrentLayout, getComponent: unauthorized[0],
injectedJS: injectedJSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
}) injectedJS: injectedJSWithCurrentLayout,
: [] })
: []
let dynamic = layoutOrPageMod?.dynamic let dynamic = layoutOrPageMod?.dynamic
...@@ -617,6 +622,7 @@ async function createComponentTreeInternal( ...@@ -617,6 +622,7 @@ async function createComponentTreeInternal(
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts,
MetadataOutlet: MetadataOutlet:
experimental.parallelRouteMetadata || isChildrenRouteKey experimental.parallelRouteMetadata || isChildrenRouteKey
? MetadataOutlet ? MetadataOutlet
......
...@@ -171,6 +171,7 @@ export interface RenderOptsPartial { ...@@ -171,6 +171,7 @@ export interface RenderOptsPartial {
parallelRouteMetadata: boolean parallelRouteMetadata: boolean
inlineCss: boolean inlineCss: boolean
prefetchInlining: PrefetchInliningConfig prefetchInlining: PrefetchInliningConfig
authInterrupts: boolean
reactBrowserBailout: boolean reactBrowserBailout: boolean
serverComponentsHmrCancellation?: boolean serverComponentsHmrCancellation?: boolean
useCacheTimeout: number useCacheTimeout: number
......
...@@ -266,6 +266,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -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. // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded, rootLayoutIncluded,
preloadCallbacks, preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet, MetadataOutlet,
isPrerendering: false, isPrerendering: false,
hintTree, hintTree,
...@@ -396,7 +397,10 @@ export async function createFullTreeForNavigation({ ...@@ -396,7 +397,10 @@ export async function createFullTreeForNavigation({
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType<{ tree: LoaderTree }> MetadataOutlet: React.ComponentType<{ tree: LoaderTree }>
}): Promise<NavigationResponseTree> { }): Promise<NavigationResponseTree> {
const { pagePath } = ctx const {
renderOpts: { experimental },
pagePath,
} = ctx
const hintTreeForInitialRender = const hintTreeForInitialRender =
ctx.renderOpts.prefetchHints?.[pagePath] ?? null ctx.renderOpts.prefetchHints?.[pagePath] ?? null
...@@ -412,6 +416,7 @@ export async function createFullTreeForNavigation({ ...@@ -412,6 +416,7 @@ export async function createFullTreeForNavigation({
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded: false, rootLayoutIncluded: false,
preloadCallbacks, preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet, MetadataOutlet,
isPrerendering: false, isPrerendering: false,
hintTree: hintTreeForInitialRender, hintTree: hintTreeForInitialRender,
......
...@@ -41,7 +41,10 @@ export type WorkStoreContext = { ...@@ -41,7 +41,10 @@ export type WorkStoreContext = {
pendingWaitUntil?: Promise<any> pendingWaitUntil?: Promise<any>
experimental: Pick< experimental: Pick<
RenderOpts['experimental'], RenderOpts['experimental'],
'isRoutePPREnabled' | 'useCacheTimeout' | 'durableUseCacheEntries' | 'isRoutePPREnabled'
| 'authInterrupts'
| 'useCacheTimeout'
| 'durableUseCacheEntries'
> >
/** /**
......
...@@ -627,6 +627,7 @@ export default abstract class Server< ...@@ -627,6 +627,7 @@ export default abstract class Server<
inlineCss: this.nextConfig.experimental.inlineCss ?? false, inlineCss: this.nextConfig.experimental.inlineCss ?? false,
prefetchInlining: prefetchInlining:
this.nextConfig.experimental.prefetchInlining ?? false, this.nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
reactBrowserBailout: reactBrowserBailout:
this.nextConfig.experimental.reactBrowserBailout ?? false, this.nextConfig.experimental.reactBrowserBailout ?? false,
serverComponentsHmrCancellation: serverComponentsHmrCancellation:
......
...@@ -1462,9 +1462,9 @@ export interface ExperimentalConfig { ...@@ -1462,9 +1462,9 @@ export interface ExperimentalConfig {
*/ */
inlineCss?: boolean inlineCss?: boolean
// TODO: Remove this config when the API is stable.
/** /**
* @deprecated `forbidden()` and `unauthorized()` are available by default. * This config allows you to enable the experimental navigation API `forbidden` and `unauthorized`.
* This option has no effect and can be removed.
*/ */
authInterrupts?: boolean authInterrupts?: boolean
...@@ -2456,6 +2456,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2456,6 +2456,7 @@ export const defaultConfig = Object.freeze({
parallelServerCompiles: false, parallelServerCompiles: false,
parallelServerBuildTraces: false, parallelServerBuildTraces: false,
ppr: false, ppr: false,
authInterrupts: false,
webpackBuildWorker: undefined, webpackBuildWorker: undefined,
webpackMemoryOptimizations: false, webpackMemoryOptimizations: false,
optimizeServerReact: true, optimizeServerReact: true,
...@@ -2575,6 +2576,7 @@ export interface NextConfigRuntime { ...@@ -2575,6 +2576,7 @@ export interface NextConfigRuntime {
| 'parallelRouteMetadata' | 'parallelRouteMetadata'
| 'inlineCss' | 'inlineCss'
| 'prefetchInlining' | 'prefetchInlining'
| 'authInterrupts'
| 'reactBrowserBailout' | 'reactBrowserBailout'
| 'useCacheTimeout' | 'useCacheTimeout'
| 'durableUseCacheEntries' | 'durableUseCacheEntries'
...@@ -2646,6 +2648,7 @@ export function getNextConfigRuntime( ...@@ -2646,6 +2648,7 @@ export function getNextConfigRuntime(
parallelRouteMetadata: ex.parallelRouteMetadata, parallelRouteMetadata: ex.parallelRouteMetadata,
inlineCss: ex.inlineCss, inlineCss: ex.inlineCss,
prefetchInlining: ex.prefetchInlining, prefetchInlining: ex.prefetchInlining,
authInterrupts: ex.authInterrupts,
reactBrowserBailout: ex.reactBrowserBailout, reactBrowserBailout: ex.reactBrowserBailout,
useCacheTimeout: ex.useCacheTimeout, useCacheTimeout: ex.useCacheTimeout,
durableUseCacheEntries: ex.durableUseCacheEntries, durableUseCacheEntries: ex.durableUseCacheEntries,
......
...@@ -245,13 +245,6 @@ function checkDeprecations( ...@@ -245,13 +245,6 @@ function checkDeprecations(
silent 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( warnOptionHasBeenDeprecated(
userConfig, userConfig,
'eslint', 'eslint',
......
...@@ -766,6 +766,7 @@ export default class DevServer extends Server { ...@@ -766,6 +766,7 @@ export default class DevServer extends Server {
nextConfigOutput: this.nextConfig.output, nextConfigOutput: this.nextConfig.output,
buildId: this.buildId, buildId: this.buildId,
deploymentId: this.deploymentId, deploymentId: this.deploymentId,
authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),
useCacheTimeout: this.nextConfig.experimental.useCacheTimeout, useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
this.nextConfig.experimental.durableUseCacheEntries this.nextConfig.experimental.durableUseCacheEntries
......
...@@ -53,6 +53,7 @@ export async function loadStaticPaths({ ...@@ -53,6 +53,7 @@ export async function loadStaticPaths({
nextConfigOutput, nextConfigOutput,
buildId, buildId,
deploymentId, deploymentId,
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
...@@ -77,6 +78,7 @@ export async function loadStaticPaths({ ...@@ -77,6 +78,7 @@ export async function loadStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string buildId: string
deploymentId: string deploymentId: string
authInterrupts: boolean
useCacheTimeout: number useCacheTimeout: number
durableUseCacheEntries: boolean durableUseCacheEntries: boolean
staticPageGenerationTimeout: number staticPageGenerationTimeout: number
...@@ -159,6 +161,7 @@ export async function loadStaticPaths({ ...@@ -159,6 +161,7 @@ export async function loadStaticPaths({
isEnsureStaticPage, isEnsureStaticPage,
buildId, buildId,
deploymentId, deploymentId,
authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
......
...@@ -334,6 +334,8 @@ export async function adapter( ...@@ -334,6 +334,8 @@ export async function adapter(
validationLevel: 'warning', validationLevel: 'warning',
experimental: { experimental: {
isRoutePPREnabled: false, isRoutePPREnabled: false,
authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts,
// Proxy doesn't fill Cache Components entries, so this value // Proxy doesn't fill Cache Components entries, so this value
// is never read. 0 is a sentinel: if something ever reads it, // is never read. 0 is a sentinel: if something ever reads it,
// the cache fill will time out immediately and surface the // the cache fill will time out immediately and surface the
......
...@@ -127,6 +127,7 @@ export class EdgeRouteModuleWrapper { ...@@ -127,6 +127,7 @@ export class EdgeRouteModuleWrapper {
// TODO: Remove validationLevel and other global config from renderOpts // TODO: Remove validationLevel and other global config from renderOpts
validationLevel: 'warning', validationLevel: 'warning',
experimental: { experimental: {
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,
// Edge runtime doesn't support Cache Components, so this value is // Edge runtime doesn't support Cache Components, so this value is
// never read. 0 is a sentinel: if something ever reads it, the cache // never read. 0 is a sentinel: if something ever reads it, the cache
// fill will time out immediately and surface the bug. // fill will time out immediately and surface the bug.
......
...@@ -23,7 +23,7 @@ export interface RequestData { ...@@ -23,7 +23,7 @@ export interface RequestData {
trailingSlash?: boolean trailingSlash?: boolean
experimental?: Pick< experimental?: Pick<
ExperimentalConfig, ExperimentalConfig,
'cacheLife' | 'clientParamParsingOrigins' 'cacheLife' | 'authInterrupts' | 'clientParamParsingOrigins'
> >
} }
page?: { page?: {
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
*/ */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
authInterrupts: true,
globalNotFound: true, globalNotFound: true,
}, },
} }
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: { experimental: {
authInterrupts: true,
instantInsights: { instantInsights: {
validationLevel: 'manual-warning', validationLevel: 'manual-warning',
}, },
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
*/ */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
authInterrupts: true,
explicitParallelRouteChildren: 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