Separate from the mail rule so that it can be taken or left. A site whose address matches
iapl({ developmentHosts }) - built in: *.dev.netscale.pl - is noindex with no env: robots.txt disallows
everything, pages carry noindex, IndexNow sends nothing, buildSecurityHeaders() adds X-Robots-Tag. Nothing
kept a development copy out of search engines until now unless somebody set the variable.
- iapl({ developmentNoindex: false }) switches it off for the project, IAPL_NOINDEX=0 for one environment
- buildSecurityHeaders({ developmentHosts, serverUrl }): next.config runs before the plugin
- the mail rule keeps its own two signals: the development pattern, and the variable itself
- changelog "what changes on upgrade", deployment.md, security.md, AGENT.md, skills
Co-Authored-By: Claude Fable 5.2 <[email protected]>
193 lines
8.0 KiB
TypeScript
193 lines
8.0 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'
|
|
import { isSiteNoindex } from './siteNoindex.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: `iapl({ 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: {
|
|
en: 'Created automatically; lets Bing and AI assistants learn about new pages right away.',
|
|
pl: 'Tworzony automatycznie; pozwala Bing i asystentom AI od razu poznać nowe strony.',
|
|
},
|
|
},
|
|
hooks: {
|
|
beforeChange: [
|
|
({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : randomKey()),
|
|
],
|
|
},
|
|
label: { en: 'IndexNow key', pl: 'Klucz IndexNow' },
|
|
},
|
|
]
|
|
|
|
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, and not a staging copy (IAPL_NOINDEX) — a staging build runs with
|
|
* NODE_ENV=production too, and its URLs must not reach Bing.
|
|
*/
|
|
function publicOrigin(baseUrl?: string): null | string {
|
|
const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '')
|
|
if (isSiteNoindex({ host: origin })) {return null}
|
|
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(`[iapl] 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('[iapl] 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('[iapl] IndexNow hook failed:', err instanceof Error ? err.message : err))
|
|
return doc
|
|
}
|
|
}
|