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 {
template,
not_found,
metadata,
forbidden,
unauthorized,
route: _,
} = &modules;
......@@ -343,6 +345,10 @@ impl AppPageLoaderTreeBuilder {
.await?;
self.write_modules_entry(AppDirModuleType::NotFound, *not_found)
.await?;
self.write_modules_entry(AppDirModuleType::Forbidden, *forbidden)
.await?;
self.write_modules_entry(AppDirModuleType::Unauthorized, *unauthorized)
.await?;
self.write_modules_entry(AppDirModuleType::Page, *page)
.await?;
self.write_modules_entry(AppDirModuleType::DefaultPage, *default)
......
......@@ -43,6 +43,10 @@ pub struct AppDirModules {
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<Vc<FileSystemPath>>,
#[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>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<Vc<FileSystemPath>>,
......@@ -62,6 +66,8 @@ impl AppDirModules {
loading: self.loading,
template: self.template,
not_found: self.not_found,
forbidden: self.forbidden,
unauthorized: self.unauthorized,
default: None,
route: None,
metadata: self.metadata.clone(),
......@@ -306,6 +312,8 @@ async fn get_directory_tree_internal(
"global-error" => modules.global_error = Some(file),
"loading" => modules.loading = Some(*file),
"template" => modules.template = Some(*file),
"forbidden" => modules.forbidden = Some(*file),
"unauthorized" => modules.unauthorized = Some(*file),
"not-found" => modules.not_found = Some(*file),
"default" => modules.default = Some(*file),
"route" => modules.route = Some(file),
......@@ -857,10 +865,23 @@ fn directory_tree_to_loader_tree_internal(
// the path).
let is_root_layout = app_path.is_root() && modules.layout.is_some();
if (is_root_directory || is_root_layout) && modules.not_found.is_none() {
modules.not_found = Some(
get_next_package(app_dir).join("dist/client/components/not-found-error.js".into()),
);
if is_root_directory || is_root_layout {
if modules.not_found.is_none() {
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 {
......
......@@ -29,6 +29,8 @@ pub enum AppDirModuleType {
Loading,
Template,
NotFound,
Forbidden,
Unauthorized,
GlobalError,
}
......@@ -42,6 +44,8 @@ impl AppDirModuleType {
AppDirModuleType::Loading => "loading",
AppDirModuleType::Template => "template",
AppDirModuleType::NotFound => "not-found",
AppDirModuleType::Forbidden => "forbidden",
AppDirModuleType::Unauthorized => "unauthorized",
AppDirModuleType::GlobalError => "global-error",
}
}
......
......@@ -1260,6 +1260,9 @@ export default async function build(
)
const isAppDynamicIOEnabled = Boolean(config.experimental.dynamicIO)
const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts
)
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
......@@ -1989,6 +1992,7 @@ export default async function build(
configFileName,
runtimeEnvConfig,
dynamicIO: isAppDynamicIOEnabled,
authInterrupts: isAuthInterruptsEnabled,
httpAgentOptions: config.httpAgentOptions,
locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale,
......@@ -2212,6 +2216,7 @@ export default async function build(
edgeInfo,
pageType,
dynamicIO: isAppDynamicIOEnabled,
authInterrupts: isAuthInterruptsEnabled,
cacheHandler: config.cacheHandler,
cacheHandlers: config.experimental.cacheHandlers,
isrFlushToDisk: ciEnvironment.hasNextSupport
......
......@@ -1214,6 +1214,7 @@ export async function buildAppStaticPaths({
page,
distDir,
dynamicIO,
authInterrupts,
configFileName,
segments,
isrFlushToDisk,
......@@ -1230,6 +1231,7 @@ export async function buildAppStaticPaths({
dir: string
page: string
dynamicIO: boolean
authInterrupts: boolean
configFileName: string
segments: AppSegment[]
distDir: string
......@@ -1312,6 +1314,7 @@ export async function buildAppStaticPaths({
experimental: {
after: false,
dynamicIO,
authInterrupts,
},
buildId,
},
......@@ -1487,6 +1490,7 @@ export async function isPageStatic({
edgeInfo,
pageType,
dynamicIO,
authInterrupts,
originalAppPath,
isrFlushToDisk,
maxMemoryCacheSize,
......@@ -1501,6 +1505,7 @@ export async function isPageStatic({
page: string
distDir: string
dynamicIO: boolean
authInterrupts: boolean
configFileName: string
runtimeEnvConfig: any
httpAgentOptions: NextConfigComplete['httpAgentOptions']
......@@ -1642,6 +1647,7 @@ export async function isPageStatic({
dir,
page,
dynamicIO,
authInterrupts,
configFileName,
segments,
distDir,
......
......@@ -54,20 +54,30 @@ export type 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 = {
layout: 'layout',
template: 'template',
error: 'error',
loading: 'loading',
'not-found': 'not-found',
'global-error': 'global-error',
...HTTP_ACCESS_FALLBACKS,
} as const
const GLOBAL_ERROR_FILE_TYPE = 'global-error'
const PAGE_SEGMENT = 'page$'
const PARALLEL_CHILDREN_SEGMENT = 'children$'
const defaultNotFoundPath = 'next/dist/client/components/not-found-error'
const defaultGlobalErrorPath = 'next/dist/client/components/error-boundary'
const defaultLayoutPath = 'next/dist/client/components/default-layout'
......@@ -142,9 +152,6 @@ async function createTreeCodeFromPath(
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath)
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0]
const hasRootNotFound = await resolver(
`${appDirPrefix}/${FILE_TYPES['not-found']}`
)
const pages: string[] = []
let rootLayout: string | undefined
......@@ -302,18 +309,35 @@ async function createTreeCodeFromPath(
return false
}) as [ValueOf<typeof FILE_TYPES>, string][]
// Add default not found error as root not found if not present
const hasNotFoundFile = definedFilePaths.some(
([type]) => type === 'not-found'
// Add default access fallback as root fallback if not present
const existedConventionNames = new Set(
definedFilePaths.map(([type]) => type)
)
// If the first layer is a group route, we treat it as root layer
const isFirstLayerGroupRoute =
segments.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 (!(hasRootNotFound && isFirstLayerGroupRoute)) {
definedFilePaths.push(['not-found', defaultNotFoundPath])
if (isRootLayer || isFirstLayerGroupRoute) {
const accessFallbackTypes = Object.keys(
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(
if (isNotFoundRoute && normalizedParallelKey === 'children') {
const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath
defaultHTTPAccessFallbackPaths['not-found']
const varName = `notFound${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, notFoundPath])
......
......@@ -276,6 +276,8 @@ export function getDefineEnv({
// Internal only so untyped to avoid discovery
(config.experimental as any).internal_disableSyncDynamicAPIWarnings ??
false,
'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':
!!config.experimental.authInterrupts,
...(isNodeOrEdgeCompilation
? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
......
......@@ -3,6 +3,7 @@
import React from 'react'
import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'
// TODO: error on using forbidden and unauthorized in root layout
export function bailOnRootNotFound() {
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 @@
* e.g. 404
* 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 { useUntrackedPathname } from '../navigation-untracked'
import {
HTTPAccessErrorStatus,
getAccessFallbackHTTPStatus,
getAccessFallbackErrorTypeByStatus,
isHTTPAccessFallbackError,
} from './http-access-fallback'
import { warnOnce } from '../../../shared/lib/utils/warn-once'
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 {
notFound?: React.ReactNode
forbidden?: React.ReactNode
unauthorized?: React.ReactNode
children: React.ReactNode
missingSlots?: Set<string>
}
......@@ -81,8 +79,9 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
static getDerivedStateFromError(error: any) {
if (isHTTPAccessFallbackError(error)) {
const httpStatus = getAccessFallbackHTTPStatus(error)
return {
triggeredStatus: getAccessFallbackHTTPStatus(error),
triggeredStatus: httpStatus,
}
}
// Re-throw if error is not for 404
......@@ -112,25 +111,49 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
}
render() {
const { notFound } = this.props
if (this.state.triggeredStatus === HTTPErrorStatus.NOT_FOUND) {
const { notFound, forbidden, unauthorized, children } = this.props
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 (
<>
<meta name="robots" content="noindex" />
{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({
notFound,
forbidden,
unauthorized,
children,
}: HTTPAccessFallbackBoundaryProps) {
// When we're rendering the missing params shell, this will return null. This
......@@ -139,12 +162,15 @@ export function HTTPAccessFallbackBoundary({
// (where these error can occur), we will get the correct pathname.
const pathname = useUntrackedPathname()
const missingSlots = useContext(MissingSlotContext)
const hasErrorFallback = !!(notFound || forbidden || unauthorized)
if (notFound) {
if (hasErrorFallback) {
return (
<HTTPAccessFallbackErrorBoundary
pathname={pathname}
notFound={notFound}
forbidden={forbidden}
unauthorized={unauthorized}
missingSlots={missingSlots}
>
{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'
......@@ -41,9 +47,12 @@ export function getAccessFallbackHTTPStatus(
export function getAccessFallbackErrorTypeByStatus(
status: number
): 'not-found' | undefined {
// TODO: support 403 and 401
): 'not-found' | 'forbidden' | 'unauthorized' | undefined {
switch (status) {
case 401:
return 'unauthorized'
case 403:
return 'forbidden'
case 404:
return 'not-found'
default:
......
......@@ -513,6 +513,8 @@ export default function OuterLayoutRouter({
templateScripts,
template,
notFound,
forbidden,
unauthorized,
}: {
parallelRouterKey: string
segmentPath: FlightSegmentPath
......@@ -523,6 +525,8 @@ export default function OuterLayoutRouter({
templateScripts: React.ReactNode | undefined
template: React.ReactNode
notFound: React.ReactNode | undefined
forbidden: React.ReactNode | undefined
unauthorized: React.ReactNode | undefined
}) {
const context = useContext(LayoutRouterContext)
if (!context) {
......@@ -579,7 +583,11 @@ export default function OuterLayoutRouter({
errorScripts={errorScripts}
>
<LoadingBoundary loading={loading}>
<HTTPAccessFallbackBoundary notFound={notFound}>
<HTTPAccessFallbackBoundary
notFound={notFound}
forbidden={forbidden}
unauthorized={unauthorized}
>
<RedirectBoundary>
<InnerLayoutRouter
parallelRouterKey={parallelRouterKey}
......
......@@ -28,5 +28,7 @@ class ReadonlyURLSearchParams extends URLSearchParams {
export { redirect, permanentRedirect, RedirectType } from './redirect'
export { notFound } from './not-found'
export { forbidden } from './forbidden'
export { unauthorized } from './unauthorized'
export { unstable_rethrow } from './unstable-rethrow'
export { ReadonlyURLSearchParams }
......@@ -269,6 +269,8 @@ export function useSelectedLayoutSegment(
// Shared components APIs
export {
notFound,
forbidden,
unauthorized,
redirect,
permanentRedirect,
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(
after: nextConfig.experimental.after ?? false,
dynamicIO: nextConfig.experimental.dynamicIO ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
},
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
}
......
......@@ -47,7 +47,9 @@ export async function exportAppRoute(
},
htmlFilepath: string,
fileWriter: FileWriter,
experimental: Required<Pick<ExperimentalConfig, 'after' | 'dynamicIO'>>,
experimental: Required<
Pick<ExperimentalConfig, 'after' | 'dynamicIO' | 'authInterrupts'>
>,
buildId: string
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute.
......
......@@ -67,7 +67,7 @@ type ViewportResolver = (
parent: ResolvingViewport
) => Viewport | Promise<Viewport>
export type MetadataErrorType = 'not-found'
export type MetadataErrorType = 'not-found' | 'forbidden' | 'unauthorized'
export type MetadataItems = [
Metadata | MetadataResolver | null,
......
......@@ -760,6 +760,7 @@ async function getRSCPayload(
getMetadataReady,
missingSlots,
preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
})
// When the `vary` response header is present with `Next-URL`, that means there's a chance
......
......@@ -39,6 +39,7 @@ export function createComponentTree(props: {
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
}): Promise<CacheNodeSeedData> {
return getTracer().trace(
NextNodeServerSpan.createComponentTree,
......@@ -74,6 +75,7 @@ async function createComponentTreeInternal({
ctx,
missingSlots,
preloadCallbacks,
authInterrupts,
}: {
createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree
......@@ -87,6 +89,7 @@ async function createComponentTreeInternal({
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
}): Promise<CacheNodeSeedData> {
const {
renderOpts: { nextConfigOutput, experimental },
......@@ -114,7 +117,15 @@ async function createComponentTreeInternal({
const { page, layoutOrPagePath, segment, modules, parallelRoutes } =
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 injectedJSWithCurrentLayout = new Set(injectedJS)
......@@ -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
if (nextConfigOutput === 'export') {
......@@ -314,6 +359,17 @@ async function createComponentTreeInternal({
if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) {
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.
......@@ -354,6 +410,14 @@ async function createComponentTreeInternal({
</>
) : 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
// otherwise we keep rendering for the prefetch.
// We also want to bail out if there's no Loading component in the tree.
......@@ -426,6 +490,7 @@ async function createComponentTreeInternal({
ctx,
missingSlots,
preloadCallbacks,
authInterrupts: authInterrupts,
})
childCacheNodeSeedData = seedData
......@@ -449,6 +514,8 @@ async function createComponentTreeInternal({
templateStyles={templateStyles}
templateScripts={templateScripts}
notFound={notFoundComponent}
forbidden={forbiddenComponent}
unauthorized={unauthorizedComponent}
/>,
childCacheNodeSeedData,
]
......@@ -622,6 +689,9 @@ async function createComponentTreeInternal({
}
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()`.
// 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.
......@@ -636,23 +706,58 @@ async function createComponentTreeInternal({
</>
),
}
const notfoundClientSegment = (
<ClientSegmentRoot
Component={SegmentComponent}
slots={notFoundParallelRouteProps}
params={currentParams}
/>
notfoundClientSegment = (
<>
{layerAssets}
<ClientSegmentRoot
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 = (
<HTTPAccessFallbackBoundary
key={cacheNodeKey}
notFound={
<>
{layerAssets}
{notfoundClientSegment}
</>
}
notFound={notfoundClientSegment}
forbidden={forbiddenClientSegment}
unauthorized={unauthorizedClientSegment}
>
{layerAssets}
{clientSegment}
......
......@@ -183,6 +183,7 @@ export interface RenderOptsPartial {
after: boolean
dynamicIO: boolean
inlineCss: boolean
authInterrupts: boolean
}
postponed?: string
......
......@@ -160,6 +160,7 @@ export async function walkTreeWithFlightRouterState({
rootLayoutIncluded,
getMetadataReady,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
}
)
......
......@@ -33,7 +33,7 @@ export type WorkStoreContext = {
pendingWaitUntil?: Promise<any>
experimental: Pick<
RenderOpts['experimental'],
'isRoutePPREnabled' | 'after' | 'dynamicIO'
'isRoutePPREnabled' | 'after' | 'dynamicIO' | 'authInterrupts'
>
/**
......
......@@ -594,6 +594,7 @@ export default abstract class Server<
after: this.nextConfig.experimental.after ?? false,
dynamicIO: this.nextConfig.experimental.dynamicIO ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
......@@ -2481,6 +2482,7 @@ export default abstract class Server<
experimental: {
after: renderOpts.experimental.after,
dynamicIO: renderOpts.experimental.dynamicIO,
authInterrupts: renderOpts.experimental.authInterrupts,
},
supportsDynamicResponse,
incrementalCache,
......
......@@ -445,6 +445,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
staticGenerationMinPagesPerWorker: z.number().int().optional(),
typedEnv: z.boolean().optional(),
serverComponentsHmrCache: z.boolean().optional(),
authInterrupts: z.boolean().optional(),
})
.optional(),
exportPathMap: z
......
......@@ -562,6 +562,12 @@ export interface ExperimentalConfig {
* Supports app-router in production mode only.
*/
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 = {
......@@ -1149,6 +1155,7 @@ export const defaultConfig: NextConfig = {
process.env.__NEXT_TEST_MODE &&
process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
),
authInterrupts: false,
reactOwnerStack: false,
webpackBuildWorker: undefined,
webpackMemoryOptimizations: false,
......
......@@ -779,6 +779,7 @@ export default class DevServer extends Server {
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output,
buildId: this.renderOpts.buildId,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
})
return pathsResult
} finally {
......
......@@ -49,6 +49,7 @@ export async function loadStaticPaths({
cacheLifeProfiles,
nextConfigOutput,
buildId,
authInterrupts,
}: {
dir: string
distDir: string
......@@ -69,6 +70,7 @@ export async function loadStaticPaths({
}
nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string
authInterrupts: boolean
}): Promise<PartialStaticPathsResult> {
// update work memory runtime-config
require('../../shared/lib/runtime-config.external').setConfig(config)
......@@ -107,6 +109,7 @@ export async function loadStaticPaths({
nextConfigOutput,
isRoutePPREnabled,
buildId,
authInterrupts,
})
} else if (!components.getStaticPaths) {
// 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) {
export async function getComponentTypeModule(
loaderTree: LoaderTree,
moduleType: 'layout' | 'not-found'
moduleType: 'layout' | 'not-found' | 'forbidden' | 'unauthorized'
) {
const { [moduleType]: module } = loaderTree[2]
if (typeof module !== 'undefined') {
......
......@@ -271,6 +271,8 @@ export async function adapter(
after: isAfterEnabled,
isRoutePPREnabled: false,
dynamicIO: false,
authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts,
},
buildId: buildId ?? '',
supportsDynamicResponse: true,
......
......@@ -118,6 +118,7 @@ export class EdgeRouteModuleWrapper {
experimental: {
after: isAfterEnabled,
dynamicIO: !!process.env.__NEXT_DYNAMIC_IO,
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,
},
buildId: '', // TODO: Populate this properly.
cacheLifeProfiles: this.nextConfig.experimental.cacheLife,
......
......@@ -15,7 +15,10 @@ export interface RequestData {
basePath?: string
i18n?: I18NConfig | null
trailingSlash?: boolean
experimental?: Pick<ExperimentalConfig, 'after' | 'cacheLife'>
experimental?: Pick<
ExperimentalConfig,
'after' | 'cacheLife' | 'authInterrupts'
>
}
page?: {
name?: string
......
......@@ -434,8 +434,8 @@ describe('Error overlay for hydration errors in App router', () => {
<InnerScrollAndFocusHandler segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary loading={null}>
<HTTPAccessFallbackBoundary notFound={[...]}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}>
<HTTPAccessFallbackBoundary notFound={[...]} forbidden={undefined} unauthorized={undefined}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} ...>
......@@ -888,7 +888,7 @@ describe('Error overlay for hydration errors in App router', () => {
if (isTurbopack) {
expect(fullPseudoHtml).toMatchInlineSnapshot(`
"...
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} unauthorized={undefined} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
......@@ -908,7 +908,7 @@ describe('Error overlay for hydration errors in App router', () => {
} else {
expect(fullPseudoHtml).toMatchInlineSnapshot(`
"...
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} missingSlots={Set}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={[...]} forbidden={undefined} unauthorized={undefined} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<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