Files
ipal-kit/docs/content.md
T

25 KiB
Raw Blame History

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

// 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 },
  ],
}
// 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:

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).

A locale the site does not have gives null (1.17.1). xx, all or * — from a URL that went past the proxy (a dotted path, the Markdown route /md/xx) or a caller — used to resolve the default locale's page under that code; now it is "not found". isSiteLocale(payload, locale) is the same check for your own code. A site without localization is not affected.

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.

A page is read at depth 2, Site settings and archive entries at depth 1, and Payload fills in every related document whatever its status. Before 1.18.0 a block, a menu or a System pages link that pointed at a page never published brought that page's title, slug and text into what the helpers answered (and llms-full printed it). Now the helpers leave such a related document out, as if it did not exist:

Shape Becomes
a single relationship null — a link resolves to nothing, a menu item drops out
a list of relationships the draft is removed from it
a polymorphic one { relationTo, value } value: null

A related document counts as a draft when it carries _status other than 'published' (a never-published or unpublished document of a collection with drafts). Documents without _status (collections without drafts, media) are never touched; the document itself is judged as before (only published pages are served). Applies to createContentHelpers (getSettings, resolveRoute, getEntries, getNotFoundPage, the page route, Markdown, MCP, llms-full), resolveRoute, getArchiveEntries, resolveNotFoundPage, collectSiteIndex and buildLlmsTxt / createLlmsTxtRoute. A preview (draft: true) keeps them.

  • What an existing site sees: a menu item, a card or a link whose page was never published disappears for visitors instead of showing a title that leads to a 404. Publish the page, or point the link elsewhere.
  • Keep the old behaviour: createContentHelpers({ draftRelations: 'keep' }), or draftRelations: 'keep' on resolveRoute / getArchiveEntries / resolveNotFoundPage / collectSiteIndex / buildLlmsTxt.
  • Building blocks: withoutDraftRelations(value) (returns the same object when nothing changes, copies only the changed path), applyDraftRelations(value, { draft, draftRelations }), type DraftRelations.

Front-end helpers — createContentHelpers

Instead of writing cached wrappers in every project:

// 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.

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:

// 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:

// 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.

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

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):

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): 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:

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/<entry>) 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:

// 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.
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?, negotiated? }) — null → 404 text/plain; otherwise text/markdown, x-robots-tag: noindex, s-maxage=3600, optional Link: <…>; rel="canonical" header. negotiated: true (the answer goes out at the page's own URL, see "content negotiation" below) sends cache-control: private, no-store and Vary: Accept instead of the public lifetime; createMarkdownRoute sets it by itself when the proxy marked the request (MARKDOWN_NEGOTIATED_HEADER).

Shorter — the whole route in one line:

// 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) + letting bots in through robots.txt.

Discoverability and content negotiation

So that an agent KNOWS about the Markdown version, announce it in the page <head> as an alternate (markdownHref keeps the /md prefix in one place):

// the page's generateMetadata
import { markdownHref } from '@intecion/ipal-kit'
return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
// → <link rel="alternate" type="text/markdown" href="/md/pl/o-nas">

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.

The negotiated answer is never cached as the page (1.18.0, security audit F3). It shares the page's URL, so a CDN that caches HTML ("Cache Everything" on Cloudflare, Varnish) would otherwise store the Markdown and serve it to every visitor of that page. The proxy marks the rewritten request, the route answers private, no-store with Vary: Accept, the rewrite carries the same headers, and the pages under the proxy matcher get Vary: Accept. /md/… keeps its public caching. Cloudflare ignores Vary for HTML — no-store is what keeps it out of the cache there. Options: markdown: { prefix: '/ai', negotiate: false } — negotiate: false serves Markdown only at /md/… (no rewrite, no Vary: Accept on pages). Verify: curl -sD- -o/dev/null -H 'Accept: text/markdown' https://<domain>/pl | grep -iE 'content-type|cache-control|vary' → text/markdown, private, no-store, Vary with Accept; or pnpm exec iapl-doctor --url https://<domain> --only live-probes (probe markdown-vary).

Manually (when you have your own proxy): the same URL serves Markdown on negotiation with the Accept header (a rewrite in the proxy):

// proxy.ts — keep the answer out of shared caches: mark the request for createMarkdownRoute and say Vary: Accept
import { appendVary, MARKDOWN_NEGOTIATED_HEADER, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from '@intecion/ipal-kit'
if (prefersMarkdown(request)) {
  const headers = new Headers(request.headers)
  headers.set(MARKDOWN_NEGOTIATED_HEADER, '1')
  const res = NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url), { request: { headers } })
  res.headers.set('cache-control', NEGOTIATED_CACHE_CONTROL)
  appendVary(res.headers, 'Accept')
  return res
}

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:

// 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:

{ "query": "nas", "locale": "pl", "count": 1,
  "results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }

No q → 400. An unknown ?locale= is the default locale — in the search, the under-construction check and the answer alike (1.17.1). 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):

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), queryLimit (1.17.1; default { length: 200, words: 10 } — SEARCH_QUERY_LIMIT): how much of the query reaches the database. Each word is one more LIKE on two columns and the text comes from a stranger, so a longer query is cut to its first words (limitQuery(query, queryLimit) shows the result); false = the whole query, as before. summaryField (e.g. 'aiSummary' — prefers the richer description from buildSummaryField over meta.description; see seo.md). Never throws (error → []).

createSearchRoute additionally takes getCachedPayload, config (required), defaultLimit (10), rateLimit, clientIp (see clientIp() in security.md), isPathVisible, queryLimit (passed to searchContent; the MCP search_content tool uses the default).

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

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.