Files
ipal-kit/src/modules/seo/indexNow.ts
T
radoslaw.smolinskiandClaude Opus 5.5 c9a50abc33 SEO/GEO tools and project requests: site index, IndexNow, page JSON-LD, fixes
GEO / SEO
- collectSiteIndex: one list of public docs per locale (pages + archive
  entries) on sitemap rules; llms.txt/llms-full and MCP list_pages now include
  blog/content entries and every language. Fixes hard-coded "## Strony" heading
  and homepage not collapsing to the locale root in llms.txt.
- Markdown frontmatter: canonical url + updated date.
- Metadata: X/Twitter card, OG image width/height/alt, og:type article with
  published/modified times for entries.
- Fix: Site Settings "defaultShareImage" was never used — now the OG fallback.
- getPageJsonLd (createContentHelpers): WebPage/CollectionPage/BlogPosting,
  BreadcrumbList from the real route, FAQPage via a project mapper.
- IndexNow (opt-in ipalKit({ indexNow: true })): submit published URLs in all
  languages, key generated in Site Integrations or INDEXNOW_KEY, key route.
- sameAs profiles in Site Settings + sameAsUrls(); sitemap <image:image>.

From project reports
- Fix: package exports were missing ./env and ./fluid.css although the docs
  import them (TS2307); regression test checks every documented subpath.
- Fix: plugins run before Payload adds its default users collection, so roles
  and 2FA had nothing to attach to — ipalKit injects an auth collection when
  the project has none (project's own one wins). Audit no longer errors on it.
- createMarkdownRoute, createSubmitAction (/server, headers injected).
- formatOpeningHours (PL/EN/DE text → schema.org), used by
  buildLocalBusinessJsonLd, which also takes a schema.org `type`.
- buildNavigationJsonLd straight from the header global.
- buildCsp googleMaps: full Maps JS API domain set; values de-duplicated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:19:08 +02:00

184 lines
7.6 KiB
TypeScript

import type { BasePayload, CollectionAfterChangeHook, Field } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/types.js'
import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js'
/**
* IndexNow — tell search engines a URL changed the moment it's published
* (Bing, Yandex, Seznam, Naver… share submissions). Bing's index feeds ChatGPT
* Search and Copilot, so new content reaches AI answers in minutes instead of
* waiting for a crawl. Google doesn't use IndexNow (it reads the sitemap).
*
* Opt-in: `ipalKit({ indexNow: true })` adds the hook to the pages and content
* collections; or add `buildIndexNowHook(…)` yourself. Needs the key file route
* (createIndexNowKeyRoute) and a key: Site Integrations → IndexNow (generated on
* the first save) or the INDEXNOW_KEY env var. Sends only from production with
* a public NEXT_PUBLIC_SERVER_URL; never blocks or fails a save.
*/
export const INDEXNOW_KEY_ENV = 'INDEXNOW_KEY'
export const INDEXNOW_KEY_PATH = '/indexnow-key.txt'
const ENDPOINT = 'https://api.indexnow.org/indexnow'
const KEY_FIELD = 'indexNowKey'
const SITE_INTEGRATIONS = 'site-integrations'
/** Site Integrations field holding the key — generated when empty. */
export const indexNowFields: Field[] = [
{
name: KEY_FIELD,
type: 'text',
admin: {
description:
'Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.',
},
hooks: {
beforeChange: [
({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : randomKey()),
],
},
},
]
function randomKey(): string {
const bytes = new Uint8Array(16)
globalThis.crypto.getRandomValues(bytes)
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
}
/** The IndexNow key: env first, then Site Integrations. Empty string when none. */
export async function getIndexNowKey(payload: BasePayload): Promise<string> {
const fromEnv = process.env[INDEXNOW_KEY_ENV]?.trim()
if (fromEnv) {return fromEnv}
try {
const doc = (await payload.findGlobal({ slug: SITE_INTEGRATIONS as never, depth: 0 })) as Record<string, unknown>
return typeof doc[KEY_FIELD] === 'string' ? (doc[KEY_FIELD]).trim() : ''
} catch {
return ''
}
}
/**
* Route serving the key file IndexNow fetches to verify ownership:
*
* // src/app/indexnow-key.txt/route.ts
* import { createIndexNowKeyRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createIndexNowKeyRoute({ getCachedPayload })
*/
export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: () => Promise<BasePayload> }) {
return async (): Promise<Response> => {
const key = await getIndexNowKey(await getCachedPayload())
if (!key) {return new Response('Not found', { status: 404 })}
return new Response(key, { headers: { 'cache-control': 'public, max-age=3600', 'content-type': 'text/plain; charset=utf-8' } })
}
}
/** True when submissions may leave this machine: production + a public https origin. */
function publicOrigin(baseUrl?: string): null | string {
const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '')
if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null}
if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null}
return origin
}
/** POST a batch of URLs to IndexNow. Never throws; logs a warning on failure. */
export async function submitToIndexNow({
baseUrl,
payload,
urls,
}: {
baseUrl?: string
payload: BasePayload
urls: string[]
}): Promise<boolean> {
const origin = publicOrigin(baseUrl)
if (!origin || urls.length === 0) {return false}
const key = await getIndexNowKey(payload)
if (!key) {return false}
try {
const res = await fetch(ENDPOINT, {
body: JSON.stringify({ host: new URL(origin).host, key, keyLocation: `${origin}${INDEXNOW_KEY_PATH}`, urlList: urls.slice(0, 10_000) }),
headers: { 'content-type': 'application/json; charset=utf-8' },
method: 'POST',
signal: AbortSignal.timeout(8000),
})
// 200 = accepted, 202 = accepted, key validation pending.
if (res.status !== 200 && res.status !== 202) {
console.warn(`[ipal] IndexNow: ${res.status} for ${urls.length} URL(s) — check the key file at ${origin}${INDEXNOW_KEY_PATH}`)
return false
}
return true
} catch (err) {
console.warn('[ipal] IndexNow: request failed:', err instanceof Error ? err.message : err)
return false
}
}
type BuildIndexNowHookArgs = {
/** Absolute origin. Default NEXT_PUBLIC_SERVER_URL. */
baseUrl?: string
config: I18nConfig
/**
* Set for an archive-backed collection (blog…): its archive page in Site
* Settings gives the URL prefix. Omit for the pages collection.
*/
contentCollection?: string
/** SiteSettings global. Default 'site-settings'. */
settingsSlug?: string
}
/** Builds a locale→slug map from a populated relationship read with locale 'all'. */
function slugsOf(rel: unknown, config: I18nConfig): Record<string, string> | undefined {
if (!rel || typeof rel !== 'object') {return undefined}
const slug = (rel as { slug?: unknown }).slug
const map = getLocalizedSlugs({ config, slugField: slug && typeof slug === 'object' ? (slug as Record<string, unknown>) : undefined })
return Object.keys(map).length ? map : undefined
}
/**
* afterChange hook: when a document is published (or a published one changes),
* submits its URL in every language to IndexNow. Drafts, noindex documents and
* non-production environments send nothing. Runs in the background — the save
* never waits for or fails on IndexNow.
*/
export function buildIndexNowHook({
baseUrl,
config,
contentCollection,
settingsSlug = 'site-settings',
}: BuildIndexNowHookArgs): CollectionAfterChangeHook {
return ({ collection, context, doc, req }) => {
if (context?.ipalSkipIndexNow) {return doc}
const row = doc as { _status?: string; id: number | string; meta?: { noindex?: boolean } | null; noindex?: boolean | null }
if ((row._status && row._status !== 'published') || row.noindex || row.meta?.noindex) {return doc}
if (!publicOrigin(baseUrl)) {return doc}
const run = async () => {
const all = (await req.payload.findByID({ id: row.id, collection: collection.slug as never, depth: 0, locale: 'all' as never })) as {
slug?: Record<string, unknown> | string
}
const slugs =
typeof all.slug === 'string'
? Object.fromEntries(getLocaleCodes(config).map((l) => [l, all.slug as string]))
: getLocalizedSlugs({ config, slugField: all.slug })
const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record<string, unknown>
const homeSlug = slugsOf(settings.homepage, config) ?? 'home'
const prefix = contentCollection ? slugsOf(settings[archiveFieldName(contentCollection)], config) : undefined
if (contentCollection && !prefix) {return}
const origin = publicOrigin(baseUrl)!
const urls = getLocaleCodes(config)
.map((locale) => buildLocalizedPath({ config, homeSlug, locale, prefix, slugs }))
.filter((p): p is string => Boolean(p))
.map((p) => `${origin}${p}`)
await submitToIndexNow({ baseUrl: origin, payload: req.payload, urls })
}
// Background: never block or fail the save.
void run().catch((err: unknown) => console.warn('[ipal] IndexNow hook failed:', err instanceof Error ? err.message : err))
return doc
}
}