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 { 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 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 }) { return async (): Promise => { 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 { 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 | 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) : 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 } 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 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 } }