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
+20
View File
@@ -8,6 +8,26 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20.
## 1.12.0
### Nowe
- **Leniwa strona 404** — `createNotFoundPage(content, { load })` + `renderNotFoundView(content, { blocks, blockProps,
fallback }, locale)` (`/rsc`) w server action projektu; `<NotFoundLoader>` (`/client`). Next wkłada drzewo
`not-found` layoutu do danych RSC KAŻDEJ strony; wariant `{ blocks }` renderował tam stronę 404 z panelu w każdym
języku (404 = strona główna, 2 języki: HTML strony głównej 195 → 146 KB gzip, dane RSC −42%). Teraz w danych jest
tylko loader, treść przychodzi przy wyświetleniu 404. `renderNotFoundView` przyjmuje tylko skonfigurowane języki.
Opis: pages.md → „Strona 404”.
### Wymaga zmian w projekcie
Nic obowiązkowego — `createNotFoundPage(content, { blocks })` działa jak dotąd. Zalecane (każdy projekt z 404
z panelu, zwłaszcza 404 = strona główna albo kilka języków):
1. `src/app/(frontend)/[locale]/notFoundView.ts` (`.tsx`, gdy `fallback` to JSX):
`'use server'` + `export async function loadNotFoundView(locale: string) { return renderNotFoundView(content,
{ blocks: blockRegistry, blockProps, fallback }, locale) }` — opcje przenieś z `not-found.tsx`.
2. `not-found.tsx`: `export default createNotFoundPage(content, { load: loadNotFoundView })`.
3. Sprawdzenie: w HTML dowolnej strony brak treści strony 404 (`self.__next_f`), a nieznany adres
(np. `/xx/test`) nadal daje 404 z treścią z panelu.
## 1.11.1
### Nowe
+6 -4
View File
@@ -52,7 +52,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| # | Obszar | Co musi być (plik) | API pluginu | Kontrola |
|---|---|---|---|---|
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, { load })` + `notFoundView.ts` (`renderNotFoundView`) | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S |
@@ -285,7 +285,8 @@ src/
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy)
not-found.tsx # createNotFoundPage(content, { blocks }) — 404 z panelu
not-found.tsx # createNotFoundPage(content, { load: loadNotFoundView }) — 404 z panelu
notFoundView.ts # 'use server' → renderNotFoundView(content, { blocks }, locale)
[[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate
(payload)/ # panel (generowany)
manifest.ts # export { manifest as default } from lib/content + force-dynamic
@@ -350,7 +351,8 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
statycznych — w blokach, komponentach, layoucie `[locale]` ani w
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
wersja na każdy język + `<LocaleView>` (pages.md).
`createNotFoundPage(content, { load })` — język z adresu, treść z server action dopiero przy 404
(wariant `{ blocks }` wkłada 404 w każdym języku do danych RSC KAŻDEJ strony — pages.md).
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
`manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
@@ -769,7 +771,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|---|---|---|
| Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md |
| Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { blocks, fallback })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { load })` + server action `renderNotFoundView(content, { blocks, fallback }, locale)` (`/rsc`) | pages.md |
| Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md |
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
+2 -1
View File
@@ -41,7 +41,8 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
`not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md).
`not-found.tsx`: `createNotFoundPage(content, { load: loadNotFoundView })` + `notFoundView.ts` z
`renderNotFoundView` (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content`
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
`images: buildImagesConfig()`,
+14 -3
View File
@@ -303,12 +303,23 @@ export const generateStaticParams = route.generateStaticParams // SSG → <hea
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
```tsx
// src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers()
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
// src/app/(frontend)/[locale]/notFoundView.ts — treść 404 z panelu w jednym języku (server action, od 1.12.0)
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, { blocks: blockRegistry /*, fallback: <h1>404</h1> */ })
export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}
// src/app/(frontend)/[locale]/not-found.tsx — 404 w języku z URL, bez headers(); treść ładowana dopiero przy 404,
// a nie w danych RSC każdej strony (pages.md → „Dlaczego leniwy”)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
```ts
+1 -1
View File
@@ -171,7 +171,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
(zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności),
- [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
export const revalidate (literał), BEZ searchParams,
- [locale]/not-found.tsx: createNotFoundPage(content, { blocks }) — BEZ headers() (pages.md).
- [locale]/not-found.tsx: createNotFoundPage(content, { load: loadNotFoundView }) + notFoundView.ts ('use server', renderNotFoundView) — BEZ headers() (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
+2 -2
View File
@@ -227,8 +227,8 @@ export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
// app/(frontend)/not-found.tsx
export default createNotFoundPage(content, { blocks: blockRegistry })
// app/(frontend)/not-found.tsx (+ notFoundView.ts z server action — pages.md)
export default createNotFoundPage(content, { load: loadNotFoundView })
// app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt
export { markdownRoute as GET } from '@/lib/content'
+34 -8
View File
@@ -62,18 +62,44 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt — `app/(frontend)/[locale]/not-found.tsx`, jedna linia (od 1.9.2):
Projekt — dwa pliki w `app/(frontend)/[locale]/` (od 1.12.0, **wariant leniwy — zalecany**):
```tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
```ts
// notFoundView.ts — server action z treścią 404 w JEDNYM języku
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, {
blocks: blockRegistry,
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
})
export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, {
blocks: blockRegistry,
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
}, locale)
}
```
```tsx
// not-found.tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
(`fallback` z JSX → plik `notFoundView.tsx`.)
**Dlaczego leniwy:** Next wkłada drzewo `not-found` layoutu do danych RSC (`self.__next_f`) **każdej** strony
pod nim — router potrzebuje go do 404 po stronie klienta. Wariant natychmiastowy renderuje tam stronę 404 z panelu
w każdym języku, więc każda strona wiezie ją w HTML (404 = strona główna przy 2 językach: HTML strony głównej
195 → 146 KB gzip, strony kontaktu 153 → 104 KB). W wariancie leniwym w danych jest tylko `<NotFoundLoader>`
(`/client`); treść przychodzi z server action dopiero, gdy 404 się wyświetla. Język z adresu (`/en/...`);
`renderNotFoundView` przyjmuje tylko skonfigurowane języki (inne → domyślny). Status 404 bez zmian; treść
pojawia się po hydratacji (strona 404 i tak nie jest indeksowana).
Wariant natychmiastowy (do 1.11.x jedyny) — treść już w HTML, za cenę rozmiaru każdej strony:
```tsx
export default createNotFoundPage(content, { blocks: blockRegistry, fallback: <h1>404</h1> })
```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`).
+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
}
+67
View File
@@ -0,0 +1,67 @@
import { isValidElement, type ReactElement } from 'react'
import { describe, expect, test, vi } from 'vitest'
vi.mock('next/navigation.js', () => ({ usePathname: () => '/en/missing' }))
import { createNotFoundPage, renderNotFoundView } from '../src/modules/frontend/pageRoute.js'
import { localeFromPath } from '../src/modules/pages/localeFromPath.js'
import { LocaleView } from '../src/modules/pages/LocaleView.js'
import { NotFoundLoader } from '../src/modules/pages/NotFoundLoader.js'
const layout = [{ id: '1', blockType: 'hero' }]
const helpers = () =>
({
getConfiguredLocales: vi.fn(async () => ['pl', 'en']),
getNotFoundPage: vi.fn(async (locale: string) => ({ layout, locale })),
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] },
}) as never as { getNotFoundPage: ReturnType<typeof vi.fn> } & Parameters<typeof renderNotFoundView>[0]
describe('localeFromPath', () => {
test('first segment when it is a locale, default otherwise', () => {
expect(localeFromPath('/en/missing', ['pl', 'en'], 'pl')).toBe('en')
expect(localeFromPath('/de/missing', ['pl', 'en'], 'pl')).toBe('pl')
expect(localeFromPath('', ['pl'], 'pl')).toBe('pl')
})
})
describe('createNotFoundPage', () => {
test('lazy (load): only the loader goes into the payload — no 404 page is read or rendered', async () => {
const h = helpers()
const load = vi.fn(async () => null)
const element = (await createNotFoundPage(h, { load })()) as ReactElement<{ load: unknown; locales: string[] }>
expect(element.type).toBe(NotFoundLoader)
expect(element.props.locales).toEqual(['pl', 'en'])
expect(element.props.load).toBe(load)
expect(h.getNotFoundPage).not.toHaveBeenCalled()
})
test('eager (blocks): one view per locale in LocaleView', async () => {
const h = helpers()
const element = (await createNotFoundPage(h, { blocks: {} })()) as ReactElement<{ views: Record<string, unknown> }>
expect(element.type).toBe(LocaleView)
expect(Object.keys(element.props.views)).toEqual(['pl', 'en'])
expect(h.getNotFoundPage).toHaveBeenCalledTimes(2)
})
})
describe('renderNotFoundView', () => {
test('renders the requested configured locale', async () => {
const h = helpers()
const node = await renderNotFoundView(h, { blocks: {} }, 'en')
expect(isValidElement(node)).toBe(true)
expect(h.getNotFoundPage).toHaveBeenCalledWith('en')
})
test('a locale from the browser outside the configured ones → default locale', async () => {
const h = helpers()
await renderNotFoundView(h, { blocks: {} }, '../admin')
await renderNotFoundView(h, { blocks: {} }, 42)
expect(h.getNotFoundPage.mock.calls).toEqual([['pl'], ['pl']])
})
test('no 404 page in the panel → fallback for that locale', async () => {
const h = helpers()
h.getNotFoundPage.mockResolvedValueOnce(null)
expect(await renderNotFoundView(h, { blocks: {}, fallback: (locale) => `missing:${locale}` }, 'en')).toBe('missing:en')
})
})