# content Collections whose entries live under an archive page — blog, portfolio, news, anything with a listing. Entries get an address like `/pl/artykuly/moj-post`, and the `artykuly` segment is not separate configuration — it is the slug of the page the editor picked as this collection's archive. ## Model — who is what ``` posts collection ──(config)──► "this is an archive collection" "Artykuły" page ──(System pages)──► "I am the archive of the posts collection" entry ──► belongs to posts, nothing more ``` An entry knows nothing about its address. The page assignment decides the address — one for the whole collection. Renaming the "Artykuły" page to "Wpisy" moves the whole section to `/pl/wpisy`, per locale, without a deploy. It works like a folder: files do not tag themselves with the folder name, the folder has the name. **You cannot add a collection from the admin panel** — Payload keeps the schema in code. A new content type is always a code change (a new collection + an entry in the config). The editor manages only the archive assignment and its address. ## Config ```ts // content.config.ts — shared by payload.config and the front end import type { ContentOption } from '@intecion/ipal-kit' export const contentConfig: ContentOption = { collections: [ { slug: 'posts', label: 'Artykuły', perPage: 10 }, { slug: 'projects', label: 'Realizacje', perPage: 6 }, ], } ``` ```ts // payload.config.ts iapl({ pages: { slug: 'pages' }, // required — the archive is a page content: contentConfig, seo: { collections: ['pages', 'posts', 'projects'] }, // entries want meta too }) ``` Each item adds to **Site settings → System pages** a relationship field "{label} — archive page" named `{slug}Archive` (`archiveFieldName('posts')` → `'postsArchive'`), pointing at the `pages.slug` collection. | Field | Default | What it does | |---|---|---| | `slug` | — (required) | slug of the client's collection | | `label` | `slug` | label of the archive field in the admin panel | | `perPage` | `10` | entries per listing page (`route.perPage`) | Without the `pages` option the archive fields are **not added** (the plugin silently skips `content`, `src/plugin.ts` ~275) — entry routing then does not work. A separate `content.config.ts` file (like `i18n.config.ts`) is needed because two places read the same declaration: payload.config (to add the archive fields) and the front end (the router). One source of truth. ## Resolving routes — resolveRoute The heart of the module. The catch-all `[[...slug]]` catches everything, and `resolveRoute` says what a given path is: ```ts import { resolveRoute } from '@intecion/ipal-kit' const route = await resolveRoute({ payload, locale: 'pl', segments: ['artykuly', 'moj-post'], page: 1, // from ?page= content: contentConfig, // pagesSlug: 'pages', settingsSlug: 'site-settings', settings (already read, depth ≥ 1), // draft: false (true = preview: latest draft, unpublished too) }) // null on 404, otherwise: // { type: 'home' | 'page', doc } // { type: 'archive', doc, collection, page, perPage } // { type: 'entry', doc, collection, archive } (archive = the archive page) ``` Without `draft: true`, documents with a `_status` other than `published` (page, archive, entry) give `null`. The page assigned as 404 in System pages also gives `null` (a real 404 instead of a soft 404). Logic: the first segment is matched against the slugs of the archive pages from System Pages. A match → we know which collection it is about. `['artykuly']` → listing of `posts`; `['artykuly','moj-post']` → an entry in `posts`; no match → a regular page. **The archive takes precedence over a page with the same slug** — otherwise the page "artykuly" would hide its own entries. **Depth is only `{archive}/{entry}`** — categories in the path would make the canonical ambiguous (the same entry under many URLs), so `/a/b/c` → null. **Slug collision:** two collections with an archive with the same slug → the first one in the `collections` list wins. A configuration error; the router does not warn. ## Front-end helpers — createContentHelpers Instead of writing cached wrappers in every project: ```ts // src/lib/content.ts import { createContentHelpers } from '@intecion/ipal-kit' import config from '@/payload.config' import { contentConfig } from '@/content.config' export const { getCachedPayload, getConfiguredLocales, getSettings, resolveRoute, getEntries } = createContentHelpers({ config, content: contentConfig }) ``` The factory returns much more (metadata, sitemap, links, route handlers) — the full list of options and `@/lib/content` keys: [frontend.md](./frontend.md). Everything is wrapped in React `cache()`, and the Payload instance is created **once** in the factory and shared — that is why it is a factory, not loose functions. Without it `cache()` would not dedupe across helpers, and Next calls generateMetadata and the page component separately. `getSettings(locale)` reads Site settings with **`depth: 1`** — relationships (logo, pages in menus, system pages) arrive as documents (`slug`, `title`), but **their** relationships arrive as IDs. The page that `resolveRoute` renders (home page, archive, regular page) is fetched separately with `depth: 2`. Need more depth in the layout (e.g. the image of a page linked in the menu)? Fetch that one document yourself instead of raising the depth of the whole global on every request — or, deliberately, `createContentHelpers({ settingsDepth: 2 })` (a cost on every request). `resolveRoute` from the factory takes `(locale, segments, page)` — it resolves the route. Fetching entries is a separate function, `getEntries` (see below), because routing and data fetching are two different responsibilities. ## Routing and fetching — separately An archive needs a list of entries; metadata does not. Resolving the route and fetching entries are two functions, composed explicitly where you need both: ```ts // generateMetadata — the route only (does not pay for the entries query) const route = await resolveRoute(locale, slug, page) // page component — the route, then entries if it is an archive const route = await resolveRoute(locale, slug, page) const entries = route?.type === 'archive' ? await getEntries(route.collection, locale, route.page, route.perPage) : null // entries: { docs, page, totalDocs, totalPages, hasPrevPage, hasNextPage } ``` `getEntries` = `getArchiveEntries` with default settings: newest first (`sort: '-createdAt'`), `depth: 1`, published only (the `_status` filter is added only in collections with drafts). Your own sort/filter: `getArchiveEntries({ payload, collection, locale, page, perPage, sort, where, depth, draft })`. `resolveRoute` returns `collection` and `perPage` — i.e. WHAT and HOW MANY to fetch — but does not fetch. Thanks to that, changing the listing's sort or filter does not touch the routing rules, and metadata does not fetch entries it would not use anyway. ## Listing The archive page is a regular page with blocks, so the listing is a **block** (yours — the plugin does not decide how the list looks). The block gets the entries through enhanceProps: ```tsx // in page.tsx — the route does not carry entries, fetch them with getEntries const entries = route.type === 'archive' ? await getEntries(route.collection, locale, route.page, route.perPage) : null const enhanceProps = ({ block }) => { if (block.blockType === 'entriesList' && entries) { return { entries, locale, archiveSlug: route.doc.slug } } return {} } ``` **`createPageRoute` (`/rsc`) does not paginate** — it always calls `resolveRoute(locale, segments, 1)` and does not read `searchParams` (`src/modules/frontend/pageRoute.tsx` ~121). An archive with `?page=` needs its own page (or a separate archive route) that reads `searchParams` — see pages.md "TRAP: await searchParams" and [frontend.md](./frontend.md). The block does not know what it lists — the route injects the entries based on which collection this page is the archive of. The same block serves `/pl/artykuly` and `/pl/realizacje`. ## Paths and pagination ```ts import { buildEntryPath, buildArchivePath, parsePageParam } from '@intecion/ipal-kit' buildEntryPath({ locale: 'pl', archiveSlug: 'artykuly', entrySlug: 'moj-post' }) // '/pl/artykuly/moj-post' buildArchivePath({ locale: 'pl', archiveSlug: 'artykuly', page: 2 }) // '/pl/artykuly?page=2' (page 1 without a query) parsePageParam(searchParams.page) // '2' → 2; junk/undefined → 1 ``` `buildEntryPath` / `buildArchivePath` **always** add `/{locale}` — also on a single-language site, where addresses have no prefix — there build the path yourself. Links to entries from `resolveLink`/`resolveNav` (links.md) get the same prefix. Pagination uses `?page=`, not `/2`. A path segment would clash with an entry with the slug "2", and `/strona/2` would add another localized segment to the configuration. Google has understood `?page=` for years, and `rel=next/prev` has been retired. The canonical of page 2 points **to itself** (`?page=2`), not to page 1 — otherwise Google would assume the entries on later pages do not exist. Hreflangs carry the same number (`/en/articles?page=2`). `createPageMetadata` handles this automatically when you pass it `page` and `content`. ## Entry metadata `createPageMetadata` with the `content` option recognizes entries by itself and builds a correct canonical/hreflang with the prefix for them (see seo.md): ```ts const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, content: contentConfig, // ← without this, entries get the wrong address }) ``` ## Language switcher `switchLocalePath` (from i18n) takes the prefix into account: a Polish entry with no EN translation leads to the EN archive (`/en/articles`), not to the home page — closest to what the visitor is looking for. ## Redirects from slug history — resolveRedirect The pair to `trackSlugHistoryHook` (see [hooks.md](./hooks.md)): the hook saves old slugs, `resolveRedirect` turns them back into 301/308, so a slug change does not give a 404. Call it in the catch-all when `resolveRoute` finds nothing: ```tsx import { resolveRoute, resolveRedirect } from '@intecion/ipal-kit' import { permanentRedirect, notFound } from 'next/navigation' const route = await resolveRoute({ /* … */ }) if (!route) { const dest = await resolveRedirect({ payload, locale, segments: slug, config: i18nConfig, homeSlug, collections: [{ slug: 'pages' }], // default [{ slug: 'pages' }] }) if (dest) permanentRedirect(dest) // HTTP 308 — equivalent to 301 for SEO notFound() } ``` Returns the target path (localized, with home collapsed via `homeSlug`) or `null`. The plugin only computes — the project calls `permanentRedirect` (the plugin does not import `next/navigation`). Any collection without a history field is skipped safely. `collections[].historyField` (default `'slugHistory'`) and `slugField` (default `'slug'`) are configurable. A never-published document (`_status: 'draft'`) does not redirect — its new slug does not leak through a redirect. Preview (`draftMode()`): `resolveRedirect({ …, draft: true })`. Limitations: only "flat" collections (slug → path). Entries in archives (`/artykuly/`) are not supported yet. If `slug` is `localized`, consider making `slugHistory` `localized` too, so the language histories do not overlap. ## Markdown per page — readability for AI (GEO) Agents (Claude's WebFetch, GPT, Perplexity) read a page reliably when they get clean Markdown instead of parsing HTML. `createMarkdownRenderer` renders a page (title + meta description + `blocks`) to Markdown; you wire it into a route that serves e.g. `/md/pl/o-nas`: ```ts // app/md/[locale]/[[...slug]]/route.ts import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' import { getPayload } from 'payload' import config from '@payload-config' const render = createMarkdownRenderer({ content }) // content = the same option as in the plugin export const dynamic = 'force-dynamic' export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) { const { locale, slug } = await params const md = await render({ payload: await getPayload({ config }), locale, slug }) return markdownResponse(md) // text/markdown or 404 } ``` How it works under the hood: - **`blocksToMarkdown(layout)`** — extraction by field-name CONVENTION (heading→`##`, subheading→`###`, body/content/intro/quote/bio/caption→text/richtext, image→`![]()`, arrays items/faq/… recursively). The section header of every library block (`header: { eyebrow, heading, intro }`, `buildSectionHeaderField`) leads its block: heading→`##`, then the intro; the eyebrow is left out. Navigation fields (ctaTarget, id, slug) are skipped. Unusual blocks: `overrides` per blockType. - **`lexicalToMarkdown(data)`** — a converter for a single richText field (bold, italics, links, lists, quotes, images). Standalone, no dependency on Payload's MD export (survives version bumps). Details: [richtext.md](./richtext.md). ```ts blocksToMarkdown(page.layout, { overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} zdjęć)` }, }) ``` `createMarkdownRenderer` options: `content`, `collection` (`'pages'`), `settingsSlug` (`'site-settings'`), `layoutField` (`'layout'`), `overrides`, `frontmatter` (default true — a YAML block with `locale`, `title`, `description`, `url`, `updated`), `baseUrl` (gives `url:` — the canonical HTML address), `config` (i18n — with one language `url:` has no `/pl`). `markdownResponse(md, { canonical? })` — `null` → 404 `text/plain`; otherwise `text/markdown`, `x-robots-tag: noindex`, `s-maxage=3600`, optional `Link: <…>; rel="canonical"` header. Shorter — the whole route in one line: ```ts // app/md/[locale]/[[...slug]]/route.ts (single-language: app/md/[[...slug]]/route.ts) export { markdownRoute as GET } from '@/lib/content' // options: createContentHelpers({ markdown }) export const dynamic = 'force-dynamic' // or without lib/content: // export const { GET } = createMarkdownRoute({ getCachedPayload, content, config: i18nConfig, baseUrl, isPathVisible }) ``` `createMarkdownRoute` / `markdownRoute`: 404 for unknown/unpublished pages, database error → 503. Under-construction mode: with `isPathVisible` (`markdownRoute` from `createContentHelpers` passes it by itself), pages hidden by Site settings → Maintenance also give 404. The full AI set: this endpoint + `llms.txt` (see [seo.md](./seo.md)) + letting bots in through robots.txt. ### Discoverability and content negotiation So that an agent KNOWS about the Markdown version, announce it in the page `` as an alternate (`markdownHref` keeps the `/md` prefix in one place): ```ts // the page's generateMetadata import { markdownHref } from '@intecion/ipal-kit' return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } // → ``` Simplest: `createContentHelpers({ …, markdownAlternate: true })` — then `generatePageMetadata` adds this link by itself (indexable pages only; prefix: `markdownAlternate: '/ai'`). **Proxy (mandatory, AGENT.md §0b):** `createProxy(i18nConfig, { NextResponse, markdown: true })`. Without it, on a multi-language site the proxy redirects `/md/pl/o-nas` to `/pl/md/pl/o-nas` (it treats `md` as a path without a language), so the Markdown route does not work. The option lets `/md/…` paths through and does the `Accept` negotiation below. Manually (when you have your own proxy): the same URL serves Markdown on negotiation with the `Accept` header (a rewrite in the proxy): ```ts // proxy.ts import { prefersMarkdown, markdownHref } from '@intecion/ipal-kit' if (prefersMarkdown(request)) { return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) } ``` `prefersMarkdown` respects q-values (a higher-weighted `text/html` wins). Change the prefix with the second argument, `markdownHref(path, '/ai')` — then remember to use the same in the route's folder name. ## Content search — searchContent / createSearchRoute One search logic (by `title` and `meta.description`, only the `collection` collection — `pages` by default; entries of `content` collections are NOT searched) powers the on-site search, the agents, and the MCP server's `search_content` tool — the same ranking everywhere. `createSearchRoute` exposes a JSON endpoint: ```ts // app/api/search/route.ts import { createSearchRoute } from '@intecion/ipal-kit' import { getCachedPayload, isPathVisible } from '@/lib/content' import { i18nConfig } from '@/i18n.config' export const dynamic = 'force-dynamic' export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, isPathVisible }) ``` Query: `?q=` (required), `?locale=`, `?limit=`. Response: ```json { "query": "nas", "locale": "pl", "count": 1, "results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] } ``` No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`) and without the page assigned as the 404 page (Site settings → System pages, read through `settingsSlug`, default `site-settings`), 10 by default (`defaultLimit`), max 50 results. Under-construction mode: pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database offline → empty result (200), not 500. **Rate limit:** 120/min per IP (in memory, per instance) → `429` with `Retry-After`; change it: `rateLimit: { max, windowMs }`, turn it off (a limiter in front, e.g. Cloudflare WAF): `rateLimit: false`. Collision with `@payloadcms/plugin-search` (the `search` collection → REST under `/api/search/...`): move the route, e.g. `app/api/site-search/route.ts`. Low `s-maxage` (60s) — fresh results, but with CDN caching. The helper itself (for your own server-side search): ```ts import { searchContent } from '@intecion/ipal-kit' const results = await searchContent({ payload, query, config, locale, limit, baseUrl }) // SearchResult[] = { title, url, description?, slug }[] ``` `searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `settingsSlug` (`'site-settings'`, for the 404 page), `locale` (default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50), `summaryField` (e.g. `'aiSummary'` — prefers the richer description from `buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws (error → `[]`). `createSearchRoute` additionally takes `getCachedPayload`, `config` (required), `defaultLimit` (10), `rateLimit`, `clientIp` (see `clientIp()` in security.md), `isPathVisible`. `listContent({ payload, config, locale, limit, … })` — the same results without a query: all published, indexable pages by title (`limit` 50, max 200). A list of pages, like the MCP `list_pages` tool. ## Exports ```ts import { resolveRoute, resolveRedirect, resolveNotFoundPage, blocksToMarkdown, createMarkdownRenderer, createMarkdownRoute, markdownResponse, MARKDOWN_PREFIX, prefersMarkdown, markdownHref, searchContent, listContent, createSearchRoute, lexicalToMarkdown, getArchiveEntries, buildArchivePath, buildEntryPath, parsePageParam, createContentHelpers, archiveFieldName, } from '@intecion/ipal-kit' import type { ContentOption, ContentCollectionOption, ResolvedRoute, ArchiveEntries, SearchResult } from '@intecion/ipal-kit' ``` ## Turn off, override, extend - Turn off: omit the `content` option — the archive fields are not created, `resolveRoute` recognizes only pages. - Per collection you override `label` and `perPage`; the archive field name (`{slug}Archive`) is fixed. - Listing: `getArchiveEntries` takes `sort`, `where`, `depth`, `draft` — your own sorting/filters without changing routing. - Markdown: `createMarkdownRenderer({ overrides, layoutField, frontmatter, collection })`, `blocksToMarkdown(…, { overrides })`; a prefix other than `/md` via `markdownHref(path, '/ai')` + `createProxy({ markdown: '/ai' })`; `createMarkdownRoute({ isPathVisible })` for construction mode. - Search: `searchContent` / `listContent` for your own endpoint; `createSearchRoute({ rateLimit: false | { max, windowMs }, collection, summaryField, isPathVisible })`. - Route depth (`{archive}/{entry}`) and pagination via `?page=` are currently fixed — a different URL scheme needs your own router.