Lazy 404: createNotFoundPage({ load }) + renderNotFoundView, NotFoundLoader

Next puts a layout's not-found tree into the RSC payload of every page under it. The eager
createNotFoundPage({ blocks }) rendered the panel's 404 page there in every locale, so with
404 = homepage each page shipped the homepage twice (homepage HTML 195 -> 146 KB gzip).
With { load } only <NotFoundLoader> is in the payload; the content comes from the project's
server action (renderNotFoundView, locale checked against configured locales) when a 404 shows.
The eager variant is unchanged. Docs: pages.md, i18n.md, AGENT.md, PROGRAMISTA, ipal-setup, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-20 00:46:44 +02:00
co-authored by Claude Opus 5.5
parent 8b35986635
commit 166bf51e53
14 changed files with 273 additions and 42 deletions
+1
View File
@@ -76,6 +76,7 @@ export {
} from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js'
export { TableOfContents } from '../modules/richtext/TableOfContents.js'
export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
+2 -2
View File
@@ -18,8 +18,8 @@ export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/Ren
export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { createNotFoundPage, createPageRoute, renderNotFoundView } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, NotFoundViewOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { extractHeadings } from '../modules/richtext/headings.js'
+66 -18
View File
@@ -7,6 +7,7 @@ import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.j
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js'
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
@@ -139,7 +140,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
}
export type NotFoundPageOptions = {
type NotFoundViewOptions = {
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
blocks: BlockComponentMap
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
@@ -147,31 +148,78 @@ export type NotFoundPageOptions = {
layoutField?: string
}
export type NotFoundPageOptions =
| {
/**
* Lazy 404 (recommended): the project's server action returning
* `renderNotFoundView(content, options, locale)`. Next puts the not-found tree
* into the RSC payload of EVERY page; with `load` that tree is a small loader
* and the content is fetched only when a 404 is shown. Without it every page
* carries the whole 404 page in every locale.
*/
load: (locale: string) => Promise<ReactNode>
}
| ({ load?: undefined } & NotFoundViewOptions)
export type { NotFoundViewOptions }
type NotFoundHelpers = Pick<ContentHelpers, 'getConfiguredLocales' | 'getNotFoundPage' | 'i18n'>
async function localesOf(helpers: NotFoundHelpers): Promise<string[]> {
const configured = await helpers.getConfiguredLocales()
return configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
}
async function notFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: string): Promise<ReactNode> {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
if (!doc || !layout?.length) {return typeof fallback === 'function' ? fallback(locale) : fallback}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} />
}
/**
* The 404 page from the panel in ONE locale — for the server action behind
* `createNotFoundPage(content, { load })`. The locale comes from the browser,
* so it is checked against the configured locales (anything else → default).
*
* // src/app/(frontend)/[locale]/notFoundView.ts
* 'use server'
* export async function loadNotFoundView(locale: string) {
* return renderNotFoundView(content, { blocks: blockRegistry }, locale)
* }
*/
export async function renderNotFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: unknown): Promise<ReactNode> {
const locales = await localesOf(helpers)
const safe = typeof locale === 'string' && locales.includes(locale) ? locale : (helpers.i18n?.defaultLocale ?? locales[0])
return notFoundView(helpers, options, safe)
}
/**
* app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the
* visitor's language, WITHOUT headers() (the route stays static): one view per
* locale rendered here, <LocaleView> picks the one from the URL.
* visitor's language, WITHOUT headers() (the route stays static).
*
* Lazy (recommended) — the content is fetched only when a 404 is shown:
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
* import { loadNotFoundView } from './notFoundView'
* export default createNotFoundPage(content, { load: loadNotFoundView })
*
* Eager — one view per locale rendered here, <LocaleView> picks the one from the
* URL; Next ships all of them in the payload of every page:
* export default createNotFoundPage(content, { blocks: blockRegistry })
*/
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPageOptions) {
return async function NotFoundPage() {
const configured = await helpers.getConfiguredLocales()
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
const locales = await localesOf(helpers)
const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
if (options.load) {
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} />
}
const eager = options
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
if (!doc || !layout?.length) {return [locale, fb] as const}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const
}),
),
await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)),
)
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
return <LocaleView defaultLocale={defaultLocale} views={views} />
}
}
+3 -3
View File
@@ -5,6 +5,8 @@ import type { ReactNode } from 'react'
// Bundlers in the project resolve the same file either way.
import { usePathname } from 'next/navigation.js'
import { localeFromPath } from './localeFromPath.js'
type LocaleViewProps = {
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
defaultLocale: string
@@ -25,8 +27,6 @@ type LocaleViewProps = {
* it also runs during SSR, so the HTML already contains the right language.
*/
export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
const pathname = usePathname() ?? ''
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = segment in views ? segment : defaultLocale
const locale = localeFromPath(usePathname() ?? '', Object.keys(views), defaultLocale)
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
}
+47
View File
@@ -0,0 +1,47 @@
'use client'
import type { ReactNode } from 'react'
// '.js' is required: `next` has no package.json "exports" (see LocaleView.tsx).
import { usePathname } from 'next/navigation.js'
import { useEffect, useState } from 'react'
import { localeFromPath } from './localeFromPath.js'
type NotFoundLoaderProps = {
defaultLocale: string
/** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */
load: (locale: string) => Promise<ReactNode>
locales: string[]
}
/**
* The 404 content, fetched only when the 404 is actually shown.
*
* Next puts the `not-found` tree of a layout into the RSC payload of EVERY page
* under it (the router needs it for a client-side 404). A 404 page with real
* content (often the homepage) rendered there in every locale multiplied the
* size of each page. Here only this small component is in the payload; the
* content comes from a server action on mount.
*/
export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) {
const pathname = usePathname() ?? ''
const locale = localeFromPath(pathname, locales, defaultLocale)
const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null)
useEffect(() => {
let active = true
load(locale)
.then((node) => {
if (active) {setView({ locale, node })}
})
.catch((error: unknown) => {
// the status is already 404 — without the content the page stays empty, the error goes to the console
console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error)
})
return () => {
active = false
}
}, [load, locale])
return <>{view?.locale === locale ? view.node : null}</>
}
+8
View File
@@ -0,0 +1,8 @@
/**
* The locale from the first URL segment (`/en/...` → `en`), or `defaultLocale`
* when the segment isn't one of `locales` (single-locale site, unknown prefix).
*/
export function localeFromPath(pathname: string, locales: readonly string[], defaultLocale: string): string {
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
return locales.includes(segment) ? segment : defaultLocale
}