Unverified Commit 37f26ac2 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add forbidden and unauthorized APIs (#72785)

parent b42f73aa
...@@ -320,6 +320,8 @@ impl AppPageLoaderTreeBuilder { ...@@ -320,6 +320,8 @@ impl AppPageLoaderTreeBuilder {
template, template,
not_found, not_found,
metadata, metadata,
forbidden,
unauthorized,
route: _, route: _,
} = &modules; } = &modules;
...@@ -343,6 +345,10 @@ impl AppPageLoaderTreeBuilder { ...@@ -343,6 +345,10 @@ impl AppPageLoaderTreeBuilder {
.await?; .await?;
self.write_modules_entry(AppDirModuleType::NotFound, *not_found) self.write_modules_entry(AppDirModuleType::NotFound, *not_found)
.await?; .await?;
self.write_modules_entry(AppDirModuleType::Forbidden, *forbidden)
.await?;
self.write_modules_entry(AppDirModuleType::Unauthorized, *unauthorized)
.await?;
self.write_modules_entry(AppDirModuleType::Page, *page) self.write_modules_entry(AppDirModuleType::Page, *page)
.await?; .await?;
self.write_modules_entry(AppDirModuleType::DefaultPage, *default) self.write_modules_entry(AppDirModuleType::DefaultPage, *default)
......
...@@ -43,6 +43,10 @@ pub struct AppDirModules { ...@@ -43,6 +43,10 @@ pub struct AppDirModules {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<Vc<FileSystemPath>>, pub template: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub forbidden: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unauthorized: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub not_found: Option<Vc<FileSystemPath>>, pub not_found: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<Vc<FileSystemPath>>, pub default: Option<Vc<FileSystemPath>>,
...@@ -62,6 +66,8 @@ impl AppDirModules { ...@@ -62,6 +66,8 @@ impl AppDirModules {
loading: self.loading, loading: self.loading,
template: self.template, template: self.template,
not_found: self.not_found, not_found: self.not_found,
forbidden: self.forbidden,
unauthorized: self.unauthorized,
default: None, default: None,
route: None, route: None,
metadata: self.metadata.clone(), metadata: self.metadata.clone(),
...@@ -306,6 +312,8 @@ async fn get_directory_tree_internal( ...@@ -306,6 +312,8 @@ async fn get_directory_tree_internal(
"global-error" => modules.global_error = Some(file), "global-error" => modules.global_error = Some(file),
"loading" => modules.loading = Some(*file), "loading" => modules.loading = Some(*file),
"template" => modules.template = Some(*file), "template" => modules.template = Some(*file),
"forbidden" => modules.forbidden = Some(*file),
"unauthorized" => modules.unauthorized = Some(*file),
"not-found" => modules.not_found = Some(*file), "not-found" => modules.not_found = Some(*file),
"default" => modules.default = Some(*file), "default" => modules.default = Some(*file),
"route" => modules.route = Some(file), "route" => modules.route = Some(file),
...@@ -857,10 +865,23 @@ fn directory_tree_to_loader_tree_internal( ...@@ -857,10 +865,23 @@ fn directory_tree_to_loader_tree_internal(
// the path). // the path).
let is_root_layout = app_path.is_root() && modules.layout.is_some(); let is_root_layout = app_path.is_root() && modules.layout.is_some();
if (is_root_directory || is_root_layout) && modules.not_found.is_none() { if is_root_directory || is_root_layout {
modules.not_found = Some( if modules.not_found.is_none() {
get_next_package(app_dir).join("dist/client/components/not-found-error.js".into()), modules.not_found = Some(
); get_next_package(app_dir).join("dist/client/components/not-found-error.js".into()),
);
}
if modules.forbidden.is_none() {
modules.forbidden = Some(
get_next_package(app_dir).join("dist/client/components/forbidden-error.js".into()),
);
}
if modules.unauthorized.is_none() {
modules.unauthorized = Some(
get_next_package(app_dir)
.join("dist/client/components/unauthorized-error.js".into()),
);
}
} }
let mut tree = AppPageLoaderTree { let mut tree = AppPageLoaderTree {
......
...@@ -29,6 +29,8 @@ pub enum AppDirModuleType { ...@@ -29,6 +29,8 @@ pub enum AppDirModuleType {
Loading, Loading,
Template, Template,
NotFound, NotFound,
Forbidden,
Unauthorized,
GlobalError, GlobalError,
} }
...@@ -42,6 +44,8 @@ impl AppDirModuleType { ...@@ -42,6 +44,8 @@ impl AppDirModuleType {
AppDirModuleType::Loading => "loading", AppDirModuleType::Loading => "loading",
AppDirModuleType::Template => "template", AppDirModuleType::Template => "template",
AppDirModuleType::NotFound => "not-found", AppDirModuleType::NotFound => "not-found",
AppDirModuleType::Forbidden => "forbidden",
AppDirModuleType::Unauthorized => "unauthorized",
AppDirModuleType::GlobalError => "global-error", AppDirModuleType::GlobalError => "global-error",
} }
} }
......
...@@ -1260,6 +1260,9 @@ export default async function build( ...@@ -1260,6 +1260,9 @@ export default async function build(
) )
const isAppDynamicIOEnabled = Boolean(config.experimental.dynamicIO) const isAppDynamicIOEnabled = Boolean(config.experimental.dynamicIO)
const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts
)
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr) const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
...@@ -1989,6 +1992,7 @@ export default async function build( ...@@ -1989,6 +1992,7 @@ export default async function build(
configFileName, configFileName,
runtimeEnvConfig, runtimeEnvConfig,
dynamicIO: isAppDynamicIOEnabled, dynamicIO: isAppDynamicIOEnabled,
authInterrupts: isAuthInterruptsEnabled,
httpAgentOptions: config.httpAgentOptions, httpAgentOptions: config.httpAgentOptions,
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
...@@ -2212,6 +2216,7 @@ export default async function build( ...@@ -2212,6 +2216,7 @@ export default async function build(
edgeInfo, edgeInfo,
pageType, pageType,
dynamicIO: isAppDynamicIOEnabled, dynamicIO: isAppDynamicIOEnabled,
authInterrupts: isAuthInterruptsEnabled,
cacheHandler: config.cacheHandler, cacheHandler: config.cacheHandler,
cacheHandlers: config.experimental.cacheHandlers, cacheHandlers: config.experimental.cacheHandlers,
isrFlushToDisk: ciEnvironment.hasNextSupport isrFlushToDisk: ciEnvironment.hasNextSupport
......
...@@ -1214,6 +1214,7 @@ export async function buildAppStaticPaths({ ...@@ -1214,6 +1214,7 @@ export async function buildAppStaticPaths({
page, page,
distDir, distDir,
dynamicIO, dynamicIO,
authInterrupts,
configFileName, configFileName,
segments, segments,
isrFlushToDisk, isrFlushToDisk,
...@@ -1230,6 +1231,7 @@ export async function buildAppStaticPaths({ ...@@ -1230,6 +1231,7 @@ export async function buildAppStaticPaths({
dir: string dir: string
page: string page: string
dynamicIO: boolean dynamicIO: boolean
authInterrupts: boolean
configFileName: string configFileName: string
segments: AppSegment[] segments: AppSegment[]
distDir: string distDir: string
...@@ -1312,6 +1314,7 @@ export async function buildAppStaticPaths({ ...@@ -1312,6 +1314,7 @@ export async function buildAppStaticPaths({
experimental: { experimental: {
after: false, after: false,
dynamicIO, dynamicIO,
authInterrupts,
}, },
buildId, buildId,
}, },
...@@ -1487,6 +1490,7 @@ export async function isPageStatic({ ...@@ -1487,6 +1490,7 @@ export async function isPageStatic({
edgeInfo, edgeInfo,
pageType, pageType,
dynamicIO, dynamicIO,
authInterrupts,
originalAppPath, originalAppPath,
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
...@@ -1501,6 +1505,7 @@ export async function isPageStatic({ ...@@ -1501,6 +1505,7 @@ export async function isPageStatic({
page: string page: string
distDir: string distDir: string
dynamicIO: boolean dynamicIO: boolean
authInterrupts: boolean
configFileName: string configFileName: string
runtimeEnvConfig: any runtimeEnvConfig: any
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
...@@ -1642,6 +1647,7 @@ export async function isPageStatic({ ...@@ -1642,6 +1647,7 @@ export async function isPageStatic({
dir, dir,
page, page,
dynamicIO, dynamicIO,
authInterrupts,
configFileName, configFileName,
segments, segments,
distDir, distDir,
......
...@@ -54,20 +54,30 @@ export type AppLoaderOptions = { ...@@ -54,20 +54,30 @@ export type AppLoaderOptions = {
} }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions> type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
const HTTP_ACCESS_FALLBACKS = {
'not-found': 'not-found',
forbidden: 'forbidden',
unauthorized: 'unauthorized',
} as const
const defaultHTTPAccessFallbackPaths = {
'not-found': 'next/dist/client/components/not-found-error',
forbidden: 'next/dist/client/components/forbidden-error',
unauthorized: 'next/dist/client/components/unauthorized-error',
} as const
const FILE_TYPES = { const FILE_TYPES = {
layout: 'layout', layout: 'layout',
template: 'template', template: 'template',
error: 'error', error: 'error',
loading: 'loading', loading: 'loading',
'not-found': 'not-found',
'global-error': 'global-error', 'global-error': 'global-error',
...HTTP_ACCESS_FALLBACKS,
} as const } as const
const GLOBAL_ERROR_FILE_TYPE = 'global-error' const GLOBAL_ERROR_FILE_TYPE = 'global-error'
const PAGE_SEGMENT = 'page$' const PAGE_SEGMENT = 'page$'
const PARALLEL_CHILDREN_SEGMENT = 'children$' const PARALLEL_CHILDREN_SEGMENT = 'children$'
const defaultNotFoundPath = 'next/dist/client/components/not-found-error'
const defaultGlobalErrorPath = 'next/dist/client/components/error-boundary' const defaultGlobalErrorPath = 'next/dist/client/components/error-boundary'
const defaultLayoutPath = 'next/dist/client/components/default-layout' const defaultLayoutPath = 'next/dist/client/components/default-layout'
...@@ -142,9 +152,6 @@ async function createTreeCodeFromPath( ...@@ -142,9 +152,6 @@ async function createTreeCodeFromPath(
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath) const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath)
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0] const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0]
const hasRootNotFound = await resolver(
`${appDirPrefix}/${FILE_TYPES['not-found']}`
)
const pages: string[] = [] const pages: string[] = []
let rootLayout: string | undefined let rootLayout: string | undefined
...@@ -302,18 +309,35 @@ async function createTreeCodeFromPath( ...@@ -302,18 +309,35 @@ async function createTreeCodeFromPath(
return false return false
}) as [ValueOf<typeof FILE_TYPES>, string][] }) as [ValueOf<typeof FILE_TYPES>, string][]
// Add default not found error as root not found if not present // Add default access fallback as root fallback if not present
const hasNotFoundFile = definedFilePaths.some( const existedConventionNames = new Set(
([type]) => type === 'not-found' definedFilePaths.map(([type]) => type)
) )
// If the first layer is a group route, we treat it as root layer // If the first layer is a group route, we treat it as root layer
const isFirstLayerGroupRoute = const isFirstLayerGroupRoute =
segments.length === 1 && segments.length === 1 &&
subSegmentPath.filter((seg) => isGroupSegment(seg)).length === 1 subSegmentPath.filter((seg) => isGroupSegment(seg)).length === 1
if ((isRootLayer || isFirstLayerGroupRoute) && !hasNotFoundFile) {
// If you already have a root not found, don't insert default not-found to group routes root if (isRootLayer || isFirstLayerGroupRoute) {
if (!(hasRootNotFound && isFirstLayerGroupRoute)) { const accessFallbackTypes = Object.keys(
definedFilePaths.push(['not-found', defaultNotFoundPath]) defaultHTTPAccessFallbackPaths
) as (keyof typeof defaultHTTPAccessFallbackPaths)[]
for (const type of accessFallbackTypes) {
const hasRootFallbackFile = await resolver(
`${appDirPrefix}/${FILE_TYPES[type]}`
)
const hasLayerFallbackFile = existedConventionNames.has(type)
// If you already have a root access error fallback, don't insert default access error boundary to group routes root
if (
// Is treated as root layout and without boundary
!(hasRootFallbackFile && isFirstLayerGroupRoute) &&
// Does not have a fallback boundary file
!hasLayerFallbackFile
) {
const defaultFallbackPath = defaultHTTPAccessFallbackPaths[type]
definedFilePaths.push([type, defaultFallbackPath])
}
} }
} }
...@@ -358,7 +382,7 @@ async function createTreeCodeFromPath( ...@@ -358,7 +382,7 @@ async function createTreeCodeFromPath(
if (isNotFoundRoute && normalizedParallelKey === 'children') { if (isNotFoundRoute && normalizedParallelKey === 'children') {
const notFoundPath = const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ?? definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath defaultHTTPAccessFallbackPaths['not-found']
const varName = `notFound${nestedCollectedDeclarations.length}` const varName = `notFound${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, notFoundPath]) nestedCollectedDeclarations.push([varName, notFoundPath])
......
...@@ -276,6 +276,8 @@ export function getDefineEnv({ ...@@ -276,6 +276,8 @@ export function getDefineEnv({
// Internal only so untyped to avoid discovery // Internal only so untyped to avoid discovery
(config.experimental as any).internal_disableSyncDynamicAPIWarnings ?? (config.experimental as any).internal_disableSyncDynamicAPIWarnings ??
false, false,
'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':
!!config.experimental.authInterrupts,
...(isNodeOrEdgeCompilation ...(isNodeOrEdgeCompilation
? { ? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`) // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import React from 'react' import React from 'react'
import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary' import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'
// TODO: error on using forbidden and unauthorized in root layout
export function bailOnRootNotFound() { export function bailOnRootNotFound() {
throw new Error('notFound() is not allowed to use in root layout') throw new Error('notFound() is not allowed to use in root layout')
} }
......
import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback'
export default function Forbidden() {
return (
<HTTPAccessErrorFallback
status={403}
message="This page could not be accessed."
/>
)
}
import {
HTTP_ERROR_FALLBACK_ERROR_CODE,
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.
*
* `forbidden()` can be used in
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
*
* Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)
*/
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.`
)
}
// eslint-disable-next-line no-throw-literal
const error = new Error(
HTTP_ERROR_FALLBACK_ERROR_CODE
) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest =
`${HTTP_ERROR_FALLBACK_ERROR_CODE};403`
throw error
}
...@@ -9,25 +9,23 @@ ...@@ -9,25 +9,23 @@
* e.g. 404 * e.g. 404
* 404 represents not found, and the fallback component pair contains the component and its styles. * 404 represents not found, and the fallback component pair contains the component and its styles.
* *
* TODO: support 401 and 403 HTTP errors.
*/ */
import React, { useContext } from 'react' import React, { useContext } from 'react'
import { useUntrackedPathname } from '../navigation-untracked' import { useUntrackedPathname } from '../navigation-untracked'
import { import {
HTTPAccessErrorStatus,
getAccessFallbackHTTPStatus, getAccessFallbackHTTPStatus,
getAccessFallbackErrorTypeByStatus,
isHTTPAccessFallbackError, isHTTPAccessFallbackError,
} from './http-access-fallback' } from './http-access-fallback'
import { warnOnce } from '../../../shared/lib/utils/warn-once' import { warnOnce } from '../../../shared/lib/utils/warn-once'
import { MissingSlotContext } from '../../../shared/lib/app-router-context.shared-runtime' import { MissingSlotContext } from '../../../shared/lib/app-router-context.shared-runtime'
const HTTPErrorStatus = {
NOT_FOUND: 404,
// TODO: support 401 and 403 HTTP errors.
} as const
interface HTTPAccessFallbackBoundaryProps { interface HTTPAccessFallbackBoundaryProps {
notFound?: React.ReactNode notFound?: React.ReactNode
forbidden?: React.ReactNode
unauthorized?: React.ReactNode
children: React.ReactNode children: React.ReactNode
missingSlots?: Set<string> missingSlots?: Set<string>
} }
...@@ -81,8 +79,9 @@ class HTTPAccessFallbackErrorBoundary extends React.Component< ...@@ -81,8 +79,9 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
static getDerivedStateFromError(error: any) { static getDerivedStateFromError(error: any) {
if (isHTTPAccessFallbackError(error)) { if (isHTTPAccessFallbackError(error)) {
const httpStatus = getAccessFallbackHTTPStatus(error)
return { return {
triggeredStatus: getAccessFallbackHTTPStatus(error), triggeredStatus: httpStatus,
} }
} }
// Re-throw if error is not for 404 // Re-throw if error is not for 404
...@@ -112,25 +111,49 @@ class HTTPAccessFallbackErrorBoundary extends React.Component< ...@@ -112,25 +111,49 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
} }
render() { render() {
const { notFound } = this.props const { notFound, forbidden, unauthorized, children } = this.props
if (this.state.triggeredStatus === HTTPErrorStatus.NOT_FOUND) { const { triggeredStatus } = this.state
const errorComponents = {
[HTTPAccessErrorStatus.NOT_FOUND]: notFound,
[HTTPAccessErrorStatus.FORBIDDEN]: forbidden,
[HTTPAccessErrorStatus.UNAUTHORIZED]: unauthorized,
}
if (triggeredStatus) {
const isNotFound =
triggeredStatus === HTTPAccessErrorStatus.NOT_FOUND && notFound
const isForbidden =
triggeredStatus === HTTPAccessErrorStatus.FORBIDDEN && forbidden
const isUnauthorized =
triggeredStatus === HTTPAccessErrorStatus.UNAUTHORIZED && unauthorized
// If there's no matched boundary in this layer, keep throwing the error by rendering the children
if (!(isNotFound || isForbidden || isUnauthorized)) {
return children
}
return ( return (
<> <>
<meta name="robots" content="noindex" /> <meta name="robots" content="noindex" />
{process.env.NODE_ENV === 'development' && ( {process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" /> <meta
name="next-error"
content={getAccessFallbackErrorTypeByStatus(triggeredStatus)}
/>
)} )}
{notFound} {errorComponents[triggeredStatus]}
</> </>
) )
} }
return this.props.children return children
} }
} }
export function HTTPAccessFallbackBoundary({ export function HTTPAccessFallbackBoundary({
notFound, notFound,
forbidden,
unauthorized,
children, children,
}: HTTPAccessFallbackBoundaryProps) { }: HTTPAccessFallbackBoundaryProps) {
// When we're rendering the missing params shell, this will return null. This // When we're rendering the missing params shell, this will return null. This
...@@ -139,12 +162,15 @@ export function HTTPAccessFallbackBoundary({ ...@@ -139,12 +162,15 @@ export function HTTPAccessFallbackBoundary({
// (where these error can occur), we will get the correct pathname. // (where these error can occur), we will get the correct pathname.
const pathname = useUntrackedPathname() const pathname = useUntrackedPathname()
const missingSlots = useContext(MissingSlotContext) const missingSlots = useContext(MissingSlotContext)
const hasErrorFallback = !!(notFound || forbidden || unauthorized)
if (notFound) { if (hasErrorFallback) {
return ( return (
<HTTPAccessFallbackErrorBoundary <HTTPAccessFallbackErrorBoundary
pathname={pathname} pathname={pathname}
notFound={notFound} notFound={notFound}
forbidden={forbidden}
unauthorized={unauthorized}
missingSlots={missingSlots} missingSlots={missingSlots}
> >
{children} {children}
......
const ALLOWED_CODES = new Set([404]) export const HTTPAccessErrorStatus = {
NOT_FOUND: 404,
FORBIDDEN: 403,
UNAUTHORIZED: 401,
}
const ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))
export const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK' export const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'
...@@ -41,9 +47,12 @@ export function getAccessFallbackHTTPStatus( ...@@ -41,9 +47,12 @@ export function getAccessFallbackHTTPStatus(
export function getAccessFallbackErrorTypeByStatus( export function getAccessFallbackErrorTypeByStatus(
status: number status: number
): 'not-found' | undefined { ): 'not-found' | 'forbidden' | 'unauthorized' | undefined {
// TODO: support 403 and 401
switch (status) { switch (status) {
case 401:
return 'unauthorized'
case 403:
return 'forbidden'
case 404: case 404:
return 'not-found' return 'not-found'
default: default:
......
...@@ -513,6 +513,8 @@ export default function OuterLayoutRouter({ ...@@ -513,6 +513,8 @@ export default function OuterLayoutRouter({
templateScripts, templateScripts,
template, template,
notFound, notFound,
forbidden,
unauthorized,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
...@@ -523,6 +525,8 @@ export default function OuterLayoutRouter({ ...@@ -523,6 +525,8 @@ export default function OuterLayoutRouter({
templateScripts: React.ReactNode | undefined templateScripts: React.ReactNode | undefined
template: React.ReactNode template: React.ReactNode
notFound: React.ReactNode | undefined notFound: React.ReactNode | undefined
forbidden: React.ReactNode | undefined
unauthorized: React.ReactNode | undefined
}) { }) {
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
if (!context) { if (!context) {
...@@ -579,7 +583,11 @@ export default function OuterLayoutRouter({ ...@@ -579,7 +583,11 @@ export default function OuterLayoutRouter({
errorScripts={errorScripts} errorScripts={errorScripts}
> >
<LoadingBoundary loading={loading}> <LoadingBoundary loading={loading}>
<HTTPAccessFallbackBoundary notFound={notFound}> <HTTPAccessFallbackBoundary
notFound={notFound}
forbidden={forbidden}
unauthorized={unauthorized}
>
<RedirectBoundary> <RedirectBoundary>
<InnerLayoutRouter <InnerLayoutRouter
parallelRouterKey={parallelRouterKey} parallelRouterKey={parallelRouterKey}
......
...@@ -28,5 +28,7 @@ class ReadonlyURLSearchParams extends URLSearchParams { ...@@ -28,5 +28,7 @@ class ReadonlyURLSearchParams extends URLSearchParams {
export { redirect, permanentRedirect, RedirectType } from './redirect' export { redirect, permanentRedirect, RedirectType } from './redirect'
export { notFound } from './not-found' export { notFound } from './not-found'
export { forbidden } from './forbidden'
export { unauthorized } from './unauthorized'
export { unstable_rethrow } from './unstable-rethrow' export { unstable_rethrow } from './unstable-rethrow'
export { ReadonlyURLSearchParams } export { ReadonlyURLSearchParams }
...@@ -269,6 +269,8 @@ export function useSelectedLayoutSegment( ...@@ -269,6 +269,8 @@ export function useSelectedLayoutSegment(
// Shared components APIs // Shared components APIs
export { export {
notFound, notFound,
forbidden,
unauthorized,
redirect, redirect,
permanentRedirect, permanentRedirect,
RedirectType, RedirectType,
......
import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback'
export default function Unauthorized() {
return (
<HTTPAccessErrorFallback
status={401}
message="You're not authorized to access this page."
/>
)
}
import {
HTTP_ERROR_FALLBACK_ERROR_CODE,
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.
*
* `unauthorized()` can be used in
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
*
*
* Read more: [Next.js Docs: `unauthorized`](https://nextjs.org/docs/app/api-reference/functions/unauthorized)
*/
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.`
)
}
// eslint-disable-next-line no-throw-literal
const error = new Error(
HTTP_ERROR_FALLBACK_ERROR_CODE
) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest =
`${HTTP_ERROR_FALLBACK_ERROR_CODE};401`
throw error
}
...@@ -359,6 +359,7 @@ async function exportAppImpl( ...@@ -359,6 +359,7 @@ async function exportAppImpl(
after: nextConfig.experimental.after ?? false, after: nextConfig.experimental.after ?? false,
dynamicIO: nextConfig.experimental.dynamicIO ?? false, dynamicIO: nextConfig.experimental.dynamicIO ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false, inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
}, },
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
} }
......
...@@ -47,7 +47,9 @@ export async function exportAppRoute( ...@@ -47,7 +47,9 @@ export async function exportAppRoute(
}, },
htmlFilepath: string, htmlFilepath: string,
fileWriter: FileWriter, fileWriter: FileWriter,
experimental: Required<Pick<ExperimentalConfig, 'after' | 'dynamicIO'>>, experimental: Required<
Pick<ExperimentalConfig, 'after' | 'dynamicIO' | 'authInterrupts'>
>,
buildId: string buildId: string
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
// Ensure that the URL is absolute. // Ensure that the URL is absolute.
......
...@@ -67,7 +67,7 @@ type ViewportResolver = ( ...@@ -67,7 +67,7 @@ type ViewportResolver = (
parent: ResolvingViewport parent: ResolvingViewport
) => Viewport | Promise<Viewport> ) => Viewport | Promise<Viewport>
export type MetadataErrorType = 'not-found' export type MetadataErrorType = 'not-found' | 'forbidden' | 'unauthorized'
export type MetadataItems = [ export type MetadataItems = [
Metadata | MetadataResolver | null, Metadata | MetadataResolver | null,
......
...@@ -760,6 +760,7 @@ async function getRSCPayload( ...@@ -760,6 +760,7 @@ async function getRSCPayload(
getMetadataReady, getMetadataReady,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
}) })
// When the `vary` response header is present with `Next-URL`, that means there's a chance // When the `vary` response header is present with `Next-URL`, that means there's a chance
......
...@@ -39,6 +39,7 @@ export function createComponentTree(props: { ...@@ -39,6 +39,7 @@ export function createComponentTree(props: {
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
return getTracer().trace( return getTracer().trace(
NextNodeServerSpan.createComponentTree, NextNodeServerSpan.createComponentTree,
...@@ -74,6 +75,7 @@ async function createComponentTreeInternal({ ...@@ -74,6 +75,7 @@ async function createComponentTreeInternal({
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts,
}: { }: {
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree loaderTree: LoaderTree
...@@ -87,6 +89,7 @@ async function createComponentTreeInternal({ ...@@ -87,6 +89,7 @@ async function createComponentTreeInternal({
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
const { const {
renderOpts: { nextConfigOutput, experimental }, renderOpts: { nextConfigOutput, experimental },
...@@ -114,7 +117,15 @@ async function createComponentTreeInternal({ ...@@ -114,7 +117,15 @@ async function createComponentTreeInternal({
const { page, layoutOrPagePath, segment, modules, parallelRoutes } = const { page, layoutOrPagePath, segment, modules, parallelRoutes } =
parseLoaderTree(tree) parseLoaderTree(tree)
const { layout, template, error, loading, 'not-found': notFound } = modules const {
layout,
template,
error,
loading,
'not-found': notFound,
forbidden,
unauthorized,
} = modules
const injectedCSSWithCurrentLayout = new Set(injectedCSS) const injectedCSSWithCurrentLayout = new Set(injectedCSS)
const injectedJSWithCurrentLayout = new Set(injectedJS) const injectedJSWithCurrentLayout = new Set(injectedJS)
...@@ -195,6 +206,40 @@ async function createComponentTreeInternal({ ...@@ -195,6 +206,40 @@ async function createComponentTreeInternal({
}) })
: [] : []
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
? await createComponentStylesAndScripts({
ctx,
filePath: forbidden[1],
getComponent: forbidden[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
const forbiddenElement = Forbidden ? (
<>
{forbiddenStyles}
<Forbidden />
</>
) : undefined
const [Unauthorized, unauthorizedStyles] =
authInterrupts && unauthorized
? await createComponentStylesAndScripts({
ctx,
filePath: unauthorized[1],
getComponent: unauthorized[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
})
: []
const unauthorizedElement = Unauthorized ? (
<>
{unauthorizedStyles}
<Unauthorized />
</>
) : undefined
let dynamic = layoutOrPageMod?.dynamic let dynamic = layoutOrPageMod?.dynamic
if (nextConfigOutput === 'export') { if (nextConfigOutput === 'export') {
...@@ -314,6 +359,17 @@ async function createComponentTreeInternal({ ...@@ -314,6 +359,17 @@ async function createComponentTreeInternal({
if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) { if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) {
errorMissingDefaultExport(pagePath, 'not-found') errorMissingDefaultExport(pagePath, 'not-found')
} }
if (typeof Forbidden !== 'undefined' && !isValidElementType(Forbidden)) {
errorMissingDefaultExport(pagePath, 'forbidden')
}
if (
typeof Unauthorized !== 'undefined' &&
!isValidElementType(Unauthorized)
) {
errorMissingDefaultExport(pagePath, 'unauthorized')
}
} }
// Handle dynamic segment params. // Handle dynamic segment params.
...@@ -354,6 +410,14 @@ async function createComponentTreeInternal({ ...@@ -354,6 +410,14 @@ async function createComponentTreeInternal({
</> </>
) : undefined ) : undefined
const forbiddenComponent = isChildrenRouteKey
? forbiddenElement
: undefined
const unauthorizedComponent = isChildrenRouteKey
? unauthorizedElement
: undefined
// if we're prefetching and that there's a Loading component, we bail out // if we're prefetching and that there's a Loading component, we bail out
// otherwise we keep rendering for the prefetch. // otherwise we keep rendering for the prefetch.
// We also want to bail out if there's no Loading component in the tree. // We also want to bail out if there's no Loading component in the tree.
...@@ -426,6 +490,7 @@ async function createComponentTreeInternal({ ...@@ -426,6 +490,7 @@ async function createComponentTreeInternal({
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts: authInterrupts,
}) })
childCacheNodeSeedData = seedData childCacheNodeSeedData = seedData
...@@ -449,6 +514,8 @@ async function createComponentTreeInternal({ ...@@ -449,6 +514,8 @@ async function createComponentTreeInternal({
templateStyles={templateStyles} templateStyles={templateStyles}
templateScripts={templateScripts} templateScripts={templateScripts}
notFound={notFoundComponent} notFound={notFoundComponent}
forbidden={forbiddenComponent}
unauthorized={unauthorizedComponent}
/>, />,
childCacheNodeSeedData, childCacheNodeSeedData,
] ]
...@@ -622,6 +689,9 @@ async function createComponentTreeInternal({ ...@@ -622,6 +689,9 @@ async function createComponentTreeInternal({
} }
if (isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot) { if (isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot) {
let notfoundClientSegment: React.ReactNode
let forbiddenClientSegment: React.ReactNode
let unauthorizedClientSegment: React.ReactNode
// TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`. // TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`.
// This ensures that a `HTTPAccessFallbackBoundary` is available for when that happens, // This ensures that a `HTTPAccessFallbackBoundary` is available for when that happens,
// but it's not ideal, as it needlessly invokes the `NotFound` component and renders the `RootLayout` twice. // but it's not ideal, as it needlessly invokes the `NotFound` component and renders the `RootLayout` twice.
...@@ -636,23 +706,58 @@ async function createComponentTreeInternal({ ...@@ -636,23 +706,58 @@ async function createComponentTreeInternal({
</> </>
), ),
} }
const notfoundClientSegment = ( notfoundClientSegment = (
<ClientSegmentRoot <>
Component={SegmentComponent} {layerAssets}
slots={notFoundParallelRouteProps} <ClientSegmentRoot
params={currentParams} Component={SegmentComponent}
/> slots={notFoundParallelRouteProps}
params={currentParams}
/>
</>
) )
}
if (Forbidden) {
const forbiddenParallelRouteProps = {
children: forbiddenElement,
}
forbiddenClientSegment = (
<>
{layerAssets}
<ClientSegmentRoot
Component={SegmentComponent}
slots={forbiddenParallelRouteProps}
params={currentParams}
/>
</>
)
}
if (Unauthorized) {
const unauthorizedParallelRouteProps = {
children: unauthorizedElement,
}
unauthorizedClientSegment = (
<>
{layerAssets}
<ClientSegmentRoot
Component={SegmentComponent}
slots={unauthorizedParallelRouteProps}
params={currentParams}
/>
</>
)
}
if (
notfoundClientSegment ||
forbiddenClientSegment ||
unauthorizedClientSegment
) {
segmentNode = ( segmentNode = (
<HTTPAccessFallbackBoundary <HTTPAccessFallbackBoundary
key={cacheNodeKey} key={cacheNodeKey}
notFound={ notFound={notfoundClientSegment}
<> forbidden={forbiddenClientSegment}
{layerAssets} unauthorized={unauthorizedClientSegment}
{notfoundClientSegment}
</>
}
> >
{layerAssets} {layerAssets}
{clientSegment} {clientSegment}
......
...@@ -183,6 +183,7 @@ export interface RenderOptsPartial { ...@@ -183,6 +183,7 @@ export interface RenderOptsPartial {
after: boolean after: boolean
dynamicIO: boolean dynamicIO: boolean
inlineCss: boolean inlineCss: boolean
authInterrupts: boolean
} }
postponed?: string postponed?: string
......
...@@ -160,6 +160,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -160,6 +160,7 @@ export async function walkTreeWithFlightRouterState({
rootLayoutIncluded, rootLayoutIncluded,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
authInterrupts: experimental.authInterrupts,
} }
) )
......
...@@ -33,7 +33,7 @@ export type WorkStoreContext = { ...@@ -33,7 +33,7 @@ export type WorkStoreContext = {
pendingWaitUntil?: Promise<any> pendingWaitUntil?: Promise<any>
experimental: Pick< experimental: Pick<
RenderOpts['experimental'], RenderOpts['experimental'],
'isRoutePPREnabled' | 'after' | 'dynamicIO' 'isRoutePPREnabled' | 'after' | 'dynamicIO' | 'authInterrupts'
> >
/** /**
......
...@@ -594,6 +594,7 @@ export default abstract class Server< ...@@ -594,6 +594,7 @@ export default abstract class Server<
after: this.nextConfig.experimental.after ?? false, after: this.nextConfig.experimental.after ?? false,
dynamicIO: this.nextConfig.experimental.dynamicIO ?? false, dynamicIO: this.nextConfig.experimental.dynamicIO ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false, inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
}, },
onInstrumentationRequestError: onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this), this.instrumentationOnRequestError.bind(this),
...@@ -2481,6 +2482,7 @@ export default abstract class Server< ...@@ -2481,6 +2482,7 @@ export default abstract class Server<
experimental: { experimental: {
after: renderOpts.experimental.after, after: renderOpts.experimental.after,
dynamicIO: renderOpts.experimental.dynamicIO, dynamicIO: renderOpts.experimental.dynamicIO,
authInterrupts: renderOpts.experimental.authInterrupts,
}, },
supportsDynamicResponse, supportsDynamicResponse,
incrementalCache, incrementalCache,
......
...@@ -445,6 +445,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -445,6 +445,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
staticGenerationMinPagesPerWorker: z.number().int().optional(), staticGenerationMinPagesPerWorker: z.number().int().optional(),
typedEnv: z.boolean().optional(), typedEnv: z.boolean().optional(),
serverComponentsHmrCache: z.boolean().optional(), serverComponentsHmrCache: z.boolean().optional(),
authInterrupts: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -562,6 +562,12 @@ export interface ExperimentalConfig { ...@@ -562,6 +562,12 @@ export interface ExperimentalConfig {
* Supports app-router in production mode only. * Supports app-router in production mode only.
*/ */
inlineCss?: boolean inlineCss?: boolean
// TODO: Remove this config when the API is stable.
/**
* This config allows you to enable the experimental navigation API `forbidden` and `unauthorized`.
*/
authInterrupts?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
...@@ -1149,6 +1155,7 @@ export const defaultConfig: NextConfig = { ...@@ -1149,6 +1155,7 @@ export const defaultConfig: NextConfig = {
process.env.__NEXT_TEST_MODE && process.env.__NEXT_TEST_MODE &&
process.env.__NEXT_EXPERIMENTAL_PPR === 'true' process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
), ),
authInterrupts: false,
reactOwnerStack: false, reactOwnerStack: false,
webpackBuildWorker: undefined, webpackBuildWorker: undefined,
webpackMemoryOptimizations: false, webpackMemoryOptimizations: false,
......
...@@ -779,6 +779,7 @@ export default class DevServer extends Server { ...@@ -779,6 +779,7 @@ export default class DevServer extends Server {
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output, nextConfigOutput: this.nextConfig.output,
buildId: this.renderOpts.buildId, buildId: this.renderOpts.buildId,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
}) })
return pathsResult return pathsResult
} finally { } finally {
......
...@@ -49,6 +49,7 @@ export async function loadStaticPaths({ ...@@ -49,6 +49,7 @@ export async function loadStaticPaths({
cacheLifeProfiles, cacheLifeProfiles,
nextConfigOutput, nextConfigOutput,
buildId, buildId,
authInterrupts,
}: { }: {
dir: string dir: string
distDir: string distDir: string
...@@ -69,6 +70,7 @@ export async function loadStaticPaths({ ...@@ -69,6 +70,7 @@ export async function loadStaticPaths({
} }
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string buildId: string
authInterrupts: boolean
}): Promise<PartialStaticPathsResult> { }): Promise<PartialStaticPathsResult> {
// update work memory runtime-config // update work memory runtime-config
require('../../shared/lib/runtime-config.external').setConfig(config) require('../../shared/lib/runtime-config.external').setConfig(config)
...@@ -107,6 +109,7 @@ export async function loadStaticPaths({ ...@@ -107,6 +109,7 @@ export async function loadStaticPaths({
nextConfigOutput, nextConfigOutput,
isRoutePPREnabled, isRoutePPREnabled,
buildId, buildId,
authInterrupts,
}) })
} else if (!components.getStaticPaths) { } else if (!components.getStaticPaths) {
// We shouldn't get to this point since the worker should only be called for // We shouldn't get to this point since the worker should only be called for
......
...@@ -40,7 +40,7 @@ export async function getLayoutOrPageModule(loaderTree: LoaderTree) { ...@@ -40,7 +40,7 @@ export async function getLayoutOrPageModule(loaderTree: LoaderTree) {
export async function getComponentTypeModule( export async function getComponentTypeModule(
loaderTree: LoaderTree, loaderTree: LoaderTree,
moduleType: 'layout' | 'not-found' moduleType: 'layout' | 'not-found' | 'forbidden' | 'unauthorized'
) { ) {
const { [moduleType]: module } = loaderTree[2] const { [moduleType]: module } = loaderTree[2]
if (typeof module !== 'undefined') { if (typeof module !== 'undefined') {
......
...@@ -271,6 +271,8 @@ export async function adapter( ...@@ -271,6 +271,8 @@ export async function adapter(
after: isAfterEnabled, after: isAfterEnabled,
isRoutePPREnabled: false, isRoutePPREnabled: false,
dynamicIO: false, dynamicIO: false,
authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts,
}, },
buildId: buildId ?? '', buildId: buildId ?? '',
supportsDynamicResponse: true, supportsDynamicResponse: true,
......
...@@ -118,6 +118,7 @@ export class EdgeRouteModuleWrapper { ...@@ -118,6 +118,7 @@ export class EdgeRouteModuleWrapper {
experimental: { experimental: {
after: isAfterEnabled, after: isAfterEnabled,
dynamicIO: !!process.env.__NEXT_DYNAMIC_IO, dynamicIO: !!process.env.__NEXT_DYNAMIC_IO,
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,
}, },
buildId: '', // TODO: Populate this properly. buildId: '', // TODO: Populate this properly.
cacheLifeProfiles: this.nextConfig.experimental.cacheLife, cacheLifeProfiles: this.nextConfig.experimental.cacheLife,
......
...@@ -15,7 +15,10 @@ export interface RequestData { ...@@ -15,7 +15,10 @@ export interface RequestData {
basePath?: string basePath?: string
i18n?: I18NConfig | null i18n?: I18NConfig | null
trailingSlash?: boolean trailingSlash?: boolean
experimental?: Pick<ExperimentalConfig, 'after' | 'cacheLife'> experimental?: Pick<
ExperimentalConfig,
'after' | 'cacheLife' | 'authInterrupts'
>
} }
page?: { page?: {
name?: string name?: string
......
...@@ -434,8 +434,8 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -434,8 +434,8 @@ describe('Error overlay for hydration errors in App router', () => {
<InnerScrollAndFocusHandler segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}> <InnerScrollAndFocusHandler segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}> <ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary loading={null}> <LoadingBoundary loading={null}>
<HTTPAccessFallbackBoundary notFound={[...]}> <HTTPAccessFallbackBoundary notFound={[...]} forbidden={undefined} unauthorized={undefined}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}> <HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} ...>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} ...> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} ...>
...@@ -888,7 +888,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -888,7 +888,7 @@ describe('Error overlay for hydration errors in App router', () => {
if (isTurbopack) { if (isTurbopack) {
expect(fullPseudoHtml).toMatchInlineSnapshot(` expect(fullPseudoHtml).toMatchInlineSnapshot(`
"... "...
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}> <HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} unauthorized={undefined} ...>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
...@@ -908,7 +908,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -908,7 +908,7 @@ describe('Error overlay for hydration errors in App router', () => {
} else { } else {
expect(fullPseudoHtml).toMatchInlineSnapshot(` expect(fullPseudoHtml).toMatchInlineSnapshot(`
"... "...
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}> <HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} unauthorized={undefined} ...>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
......
import { forbidden } from 'next/navigation'
// avoid static generation to fill the dynamic params
export const dynamic = 'force-dynamic'
export default async function Page(props) {
const params = await props.params
const { id } = params
if (id === '403') {
forbidden()
}
return <p id="page">{`dynamic-layout-without-forbidden [id]`}</p>
}
export default function Layout({ children }) {
return (
<div>
<h1>Dynamic with Layout</h1>
{children}
</div>
)
}
export default function Page() {
return <div>dynamic-with-layout</div>
}
export default function Forbidden() {
return <div id="forbidden">{`dynamic/[id] forbidden`}</div>
}
import { forbidden } from 'next/navigation'
export default async function Page(props) {
const params = await props.params
const { id } = params
if (id === '403') {
forbidden()
}
return <p id="page">{`dynamic [id]`}</p>
}
export default function Test() {
return <div>dynamic</div>
}
export default function Forbidden() {
return (
<>
<h1>Root Forbidden</h1>
<div id="timestamp">{Date.now()}</div>
</>
)
}
export default function Layout({ children }) {
return (
<html>
<head />
<body>
<header>
<nav id="layout-nav">Navbar</nav>
</header>
<main>{children}</main>
<footer>
<p id="layout-footer">Footer</p>
</footer>
</body>
</html>
)
}
export default function Page() {
return <h1>My page</h1>
}
import { nextTestSetup } from 'e2e-utils'
describe('app dir - forbidden with customized boundary', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should match dynamic route forbidden boundary correctly', async () => {
// `/dynamic` display works
const browserDynamic = await next.browser('/dynamic')
expect(await browserDynamic.elementByCss('main').text()).toBe('dynamic')
// `/dynamic/403` calling forbidden() will match the same level forbidden boundary
const browserError = await next.browser('/dynamic/403')
expect(await browserError.elementByCss('#forbidden').text()).toBe(
'dynamic/[id] forbidden'
)
const browserDynamicId = await next.browser('/dynamic/123')
expect(await browserDynamicId.elementByCss('#page').text()).toBe(
'dynamic [id]'
)
})
it('should escalate forbidden to parent layout if no forbidden boundary present in current layer', async () => {
const browserDynamic = await next.browser(
'/dynamic-layout-without-forbidden'
)
expect(await browserDynamic.elementByCss('h1').text()).toBe(
'Dynamic with Layout'
)
// no forbidden boundary in /dynamic-layout-without-forbidden, escalate to parent layout to render root forbidden
const browserDynamicId = await next.browser(
'/dynamic-layout-without-forbidden/403'
)
expect(await browserDynamicId.elementByCss('h1').text()).toBe(
'Root Forbidden'
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
import { forbidden } from 'next/navigation'
export default async function Page(props) {
const params = await props.params
if (params.id === '403') {
forbidden()
}
return <p id="page">{`group-dynamic [id]`}</p>
}
export default function RootLayout({ children }) {
return <div className="group-root-layout">{children}</div>
}
'use client'
import { useSearchParams, forbidden } from 'next/navigation'
export default function ForbiddenTrigger() {
const searchParams = useSearchParams()
if (searchParams.get('root-forbidden')) {
forbidden()
}
return null
}
'use client'
import { useState, Suspense } from 'react'
import { forbidden } from 'next/navigation'
import ForbiddenTrigger from './forbidden-trigger'
export default function Root({ children }) {
const [clicked, setClicked] = useState(false)
if (clicked) {
forbidden()
}
return (
<html className="root-layout-html">
<body>
<Suspense fallback={<div>Loading...</div>}>
<ForbiddenTrigger />
</Suspense>
<button id="trigger-forbidden" onClick={() => setClicked(true)}>
Click to forbidden
</button>
{children}
</body>
</html>
)
}
export const dynamic = 'force-dynamic'
import { forbidden } from 'next/navigation'
export async function generateMetadata() {
forbidden()
}
export default function layout({ children }) {
return children
}
export default function page() {
return 'not found metadata page'
}
import { forbidden } from 'next/navigation'
export default function page() {
forbidden()
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<p>hello world</p>
<div>
<Link id="navigate-forbidden" href="/navigate-forbidden">
navigate to page calling forbidden()
</Link>
</div>
<div>
<Link id="metadata-layout-forbidden" href="/metadata-layout-forbidden">
navigate to layout with metadata API calling forbidden()
</Link>
</div>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
} from 'next-test-utils'
describe('app dir - forbidden with default forbidden boundary', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
// TODO: error forbidden usage in root layout
it.skip('should error on client forbidden from root layout in browser', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#trigger-forbidden').click()
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxDescription(browser)).toMatch(
/forbidden\(\) is not allowed to use in root layout/
)
}
})
// TODO: error forbidden usage in root layout
it.skip('should error on server forbidden from root layout on server-side', async () => {
const browser = await next.browser('/?root-forbidden=1')
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxDescription(browser)).toBe(
'Error: forbidden() is not allowed to use in root layout'
)
}
})
it('should be able to navigate to page calling forbidden', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#navigate-forbidden').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('403')
expect(await browser.elementByCss('h2').text()).toBe(
'This page could not be accessed.'
)
})
it('should be able to navigate to page with calling forbidden in metadata', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#metadata-layout-forbidden').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('403')
expect(await browser.elementByCss('h2').text()).toBe(
'This page could not be accessed.'
)
})
it('should render default forbidden for group routes if forbidden is not defined', async () => {
const browser = await next.browser('/group-dynamic/123')
expect(await browser.elementByCss('#page').text()).toBe(
'group-dynamic [id]'
)
await browser.loadPage(next.url + '/group-dynamic/403')
await assertNoRedbox(browser)
await browser.waitForElementByCss('.group-root-layout')
expect(await browser.elementByCss('.next-error-h1').text()).toBe('403')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
import { unauthorized } from 'next/navigation'
export default async function Page(props) {
const params = await props.params
const { id } = params
if (id === '401') {
unauthorized()
}
return <p id="page">{`dynamic-layout-without-unauthorized [id]`}</p>
}
export default function Layout({ children }) {
return (
<div>
<h1>Dynamic with Layout</h1>
{children}
</div>
)
}
export default function Page() {
return <div>dynamic-with-layout</div>
}
import { unauthorized } from 'next/navigation'
export default async function Page(props) {
const params = await props.params
const { id } = params
if (id === '401') {
unauthorized()
}
return <p id="page">{`dynamic [id]`}</p>
}
export default function Unauthorized() {
return <div id="unauthorized">{`dynamic/[id] unauthorized`}</div>
}
export default function Test() {
return <div>dynamic</div>
}
export default function Layout({ children }) {
return (
<html>
<head />
<body>
<header>
<nav id="layout-nav">Navbar</nav>
</header>
<main>{children}</main>
<footer>
<p id="layout-footer">Footer</p>
</footer>
</body>
</html>
)
}
export default function Page() {
return <h1>My page</h1>
}
export default function Forbidden() {
return (
<>
<h1>Root Unauthorized</h1>
<div id="timestamp">{Date.now()}</div>
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('app dir - unauthorized - basic', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should match dynamic route unauthorized boundary correctly', async () => {
// `/dynamic` display works
const browserDynamic = await next.browser('/dynamic')
expect(await browserDynamic.elementByCss('main').text()).toBe('dynamic')
// `/dynamic/401` calling unauthorized() will match the same level unauthorized boundary
const browserError = await next.browser('/dynamic/401')
expect(await browserError.elementByCss('#unauthorized').text()).toBe(
'dynamic/[id] unauthorized'
)
const browserDynamicId = await next.browser('/dynamic/123')
expect(await browserDynamicId.elementByCss('#page').text()).toBe(
'dynamic [id]'
)
})
it('should escalate unauthorized to parent layout if no unauthorized boundary present in current layer', async () => {
const browserDynamic = await next.browser(
'/dynamic-layout-without-unauthorized'
)
expect(await browserDynamic.elementByCss('h1').text()).toBe(
'Dynamic with Layout'
)
// no unauthorized boundary in /dynamic-layout-without-unauthorized, escalate to parent layout to render root unauthorized
const browserDynamicId = await next.browser(
'/dynamic-layout-without-unauthorized/401'
)
expect(await browserDynamicId.elementByCss('h1').text()).toBe(
'Root Unauthorized'
)
})
})
import { unauthorized } from 'next/navigation'
export default async function Page(props) {
const params = await props.params
if (params.id === '401') {
unauthorized()
}
return <p id="page">{`group-dynamic [id]`}</p>
}
export default function RootLayout({ children }) {
return <div className="group-root-layout">{children}</div>
}
'use client'
import { useState, Suspense } from 'react'
import { unauthorized } from 'next/navigation'
import ForbiddenTrigger from './unauthorized-trigger'
export default function Root({ children }) {
const [clicked, setClicked] = useState(false)
if (clicked) {
unauthorized()
}
return (
<html className="root-layout-html">
<body>
<Suspense fallback={<div>Loading...</div>}>
<ForbiddenTrigger />
</Suspense>
<button id="trigger-unauthorized" onClick={() => setClicked(true)}>
Click to unauthorized
</button>
{children}
</body>
</html>
)
}
export const dynamic = 'force-dynamic'
import { unauthorized } from 'next/navigation'
export async function generateMetadata() {
unauthorized()
}
export default function layout({ children }) {
return children
}
export default function page() {
return 'not found metadata page'
}
import { unauthorized } from 'next/navigation'
export default function page() {
unauthorized()
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<p>hello world</p>
<div>
<Link id="navigate-unauthorized" href="/navigate-unauthorized">
navigate to page calling unauthorized()
</Link>
</div>
<div>
<Link
id="metadata-layout-unauthorized"
href="/metadata-layout-unauthorized"
>
navigate to layout with metadata API calling unauthorized()
</Link>
</div>
</div>
)
}
'use client'
import { useSearchParams, unauthorized } from 'next/navigation'
export default function ForbiddenTrigger() {
const searchParams = useSearchParams()
if (searchParams.get('root-unauthorized')) {
unauthorized()
}
return null
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
authInterrupts: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
} from 'next-test-utils'
describe('app dir - unauthorized with default unauthorized boundary', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
// TODO: error unauthorized usage in root layout
it.skip('should error on client unauthorized from root layout in browser', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#trigger-unauthorized').click()
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxDescription(browser)).toMatch(
/unauthorized\(\) is not allowed to use in root layout/
)
}
})
// TODO: error unauthorized usage in root layout
it.skip('should error on server unauthorized from root layout on server-side', async () => {
const browser = await next.browser('/?root-unauthorized=1')
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxDescription(browser)).toBe(
'Error: unauthorized() is not allowed to use in root layout'
)
}
})
it('should be able to navigate to page calling unauthorized', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#navigate-unauthorized').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('401')
expect(await browser.elementByCss('h2').text()).toBe(
`You're not authorized to access this page.`
)
})
it('should be able to navigate to page with calling unauthorized in metadata', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#metadata-layout-unauthorized').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('401')
expect(await browser.elementByCss('h2').text()).toBe(
`You're not authorized to access this page.`
)
})
it('should render default unauthorized for group routes if unauthorized is not defined', async () => {
const browser = await next.browser('/group-dynamic/123')
expect(await browser.elementByCss('#page').text()).toBe(
'group-dynamic [id]'
)
await browser.loadPage(next.url + '/group-dynamic/401')
await assertNoRedbox(browser)
await browser.waitForElementByCss('.group-root-layout')
expect(await browser.elementByCss('.next-error-h1').text()).toBe('401')
})
})
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