# seo — Agent usage Configure a coding agent for @nexload-sdk/seo. **Topic:** agents **Package:** `@nexload-sdk/seo` v1.0.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/seo/agents/ ## Install matching skills Install the skills whose triggers match the task. ### seo [Trigger](https://github.com/gecut/nexload-sdk/blob/main/skills/seo/SKILL.md) ```text Use when adding or reviewing SEO in a Payload CMS + Next.js App Router project with @nexload-sdk/seo: page metadata, canonical URLs, Open Graph, JSON-LD (Product, Article, Organization, BreadcrumbList), sitemap.ts, robots.ts, AI crawler rules (GPTBot, ClaudeBot, OAI-SearchBot, PerplexityBot), noindex vs robots.txt, Persian or percent-encoded slugs, IRT/IRR prices in schema, a seo-settings admin screen, publishedAt/contentUpdatedAt freshness, or automatic redirects when a slug changes. Also use when a sitemap is empty because one source failed, a title template applies twice, or old URLs 404 after a rename. Do not use for cache revalidation (use payload-revalidate), Persian text normalization (use persian), or logging (use logger). ``` ```bash npx skills add gecut/nexload-sdk --skill seo ``` The `seo` skill covers the three-entry split (`.`, `./next`, `./payload`), CMS endpoints ownership (`overrideAccess: false` and published filters), `resolveSeo` metadata and JSON-LD rules, `createSitemap` fault isolation and pagination, `createRobots` AI crawler presets, `proxy.ts` 308 redirects with `toRedirectKey`, indexing vs crawling, Persian URL handling, v1 startup errors, and HTTP verification checks. ## Project AGENTS.md ```markdown For @nexload-sdk/seo, load seo when its trigger matches. Read the package bundle and check public exports against the installed version before editing. ``` ## Package context [Scoped Markdown bundle](/nexload-sdk/packages/seo/llms.txt). ## Prompts ```text Wire @nexload-sdk/seo for my posts collection, Payload /api/seo/* endpoints, and Next.js metadata, sitemap, robots, and proxy.ts using the seo skill. ``` ```text Review my @nexload-sdk/seo setup for Persian URLs, noindex vs robots.txt, and sitemap fault isolation. Check against the v1 startup errors and limits. ``` --- # API Reference & Compatibility Public exports, runtime constraints, and logging events. **Topic:** api **Package:** `@nexload-sdk/seo` v1.0.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/seo/api/ The inventory is generated from the package source exports across `.`, `./next`, and `./payload`. ## Functions ### `createRobots` ```ts createRobots(options: { site: SeoSite; disallow?: string[]; }) => MetadataRoute.Robots ``` **Exported from:** `@nexload-sdk/seo/next` Generate Next.js `robots.txt` rules with AI crawler presets and baseline disallows. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/next/robots.ts#L56) ### `createSitemap` ```ts createSitemap(options: { site: SeoSite; sources: Record; logger?: Logger; }) => () => Promise ``` **Exported from:** `@nexload-sdk/seo/next` Create a Next.js sitemap collector with fault isolation, pagination, and deduplication. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/next/sitemap.ts#L132) ### `nexloadSeo` ```ts nexloadSeo(options: NexloadSeoOptions) => Plugin ``` **Exported from:** `@nexload-sdk/seo/payload` Payload CMS plugin that installs SEO meta fields, `seo-settings` global, and Persian labels. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/payload/plugin.ts#L10) ### `resolveSeo` ```ts resolveSeo(doc: SeoDocument, site: SeoSite, options?: { logger?: Logger; }) => { metadata: Metadata; jsonLd: string | null; } ``` **Exported from:** `@nexload-sdk/seo/next` Resolve Next.js `Metadata` and JSON-LD script payload for a document and site. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/next/resolve.ts#L165) ### `toRedirectKey` ```ts toRedirectKey(path: string) => string ``` **Exported from:** `@nexload-sdk/seo` Normalize a path into a canonical redirect lookup key with decoded segments and preserved separators. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/url.ts#L128) ### `toSeoDocument` ```ts toSeoDocument(doc: SeoSourceDoc, options: { path: string; entity?: SeoEntity; breadcrumbs?: SeoDocument["breadcrumbs"]; }) => SeoDocument ``` **Exported from:** `@nexload-sdk/seo` Project a Payload collection document into a normalized `SeoDocument` contract. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/document.ts#L41) ### `toSeoSite` ```ts toSeoSite(settings: SeoSettingsDoc | null | undefined, options: { url: string; }) => SeoSite ``` **Exported from:** `@nexload-sdk/seo` Project a Payload `seo-settings` global document into a normalized `SeoSite` contract. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/site.ts#L103) ## Types ### `NexloadSeoCollectionOptions` ```ts type NexloadSeoCollectionOptions = { freshness?: string[]; path?: (doc: { slug?: string | null } & Record) => string; }; ``` **Exported from:** `@nexload-sdk/seo/payload` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/payload/options.ts#L7) ### `NexloadSeoOptions` ```ts type NexloadSeoOptions = { siteUrl: string; settingsAccess: { update: NonNullable; read?: GlobalAccess["read"]; }; collections: Record; uploadsCollection?: string; redirects?: boolean; sitemapSources?: string[]; }; ``` **Exported from:** `@nexload-sdk/seo/payload` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/payload/options.ts#L12) ### `SeoAiCrawlerPolicy` ```ts type SeoAiCrawlerPolicy = "allow-all" | "search-only" | "block-all-ai"; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L33) ### `SeoDocument` ```ts type SeoDocument = { id: string; path: string; title: string; meta: { title?: string; description?: string; image?: SeoImage; canonicalUrl?: string; noIndex?: boolean; noFollow?: boolean; noSnippet?: boolean; }; publishedAt?: string; contentUpdatedAt?: string; breadcrumbs?: ReadonlyArray<{ name: string; path: string }>; entity?: SeoEntity; }; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L9) ### `SeoEntity` ```ts type SeoEntity = | { kind: "article"; author: { id: string; name: string } } | { kind: "product"; sku: string; images: string[]; price?: Money; inStock: boolean }; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L5) ### `SeoImage` ```ts type SeoImage = { url: string; alt: string; width?: number; height?: number }; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L3) ### `SeoRoute` ```ts type SeoRoute = | { kind: "page"; page: SeoDocument } | { kind: "redirect"; location: string } | { kind: "missing" }; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L28) ### `SeoSettingsDoc` ```ts type SeoSettingsDoc = { general?: { siteName?: string | null; titleTemplate?: string | null; defaultImage?: SeoUploadValue; indexing?: boolean | null; verification?: { google?: string | null; bing?: string | null; yandex?: string | null; } | null; } | null; organization?: { name?: string | null; logo?: SeoUploadValue; sameAs?: ReadonlyArray<{ url?: string | null }> | null; } | null; robots?: { aiCrawlers?: SeoAiCrawlerPolicy | null; disallow?: ReadonlyArray<{ path?: string | null }> | null; rules?: ReadonlyArray<{ userAgent?: string | null; allow?: ReadonlyArray<{ path?: string | null }> | null; disallow?: ReadonlyArray<{ path?: string | null }> | null; }> | null; } | null; sitemap?: { disabledSources?: ReadonlyArray | null; excludePaths?: ReadonlyArray<{ path?: string | null }> | null; images?: boolean | null; } | null; }; ``` **Exported from:** `@nexload-sdk/seo` JSON of the `seo-settings` global (Payload REST, depth=1). Every field optional. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L60) ### `SeoSite` ```ts type SeoSite = { url: string; name: string; titleTemplate: string; defaultImage?: SeoImage; organization: { name: string; logoUrl?: string; sameAs: string[] }; indexing: boolean; verification: { google?: string; bing?: string; yandex?: string }; robots: { aiCrawlers: SeoAiCrawlerPolicy; disallow: string[]; rules: ReadonlyArray<{ userAgent: string; allow: string[]; disallow: string[] }>; }; sitemap: { disabledSources: string[]; excludePaths: string[]; images: boolean }; }; ``` **Exported from:** `@nexload-sdk/seo` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L35) ### `SeoSitemapSource` ```ts type SeoSitemapSource = ( page: number, ) => Promise<{ docs: SeoDocument[]; hasNextPage: boolean }>; ``` **Exported from:** `@nexload-sdk/seo/next` Public type exported by @nexload-sdk/seo. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/next/sitemap.ts#L14) ### `SeoSourceDoc` ```ts type SeoSourceDoc = { id: string | number; title?: string | null; publishedAt?: string | null; contentUpdatedAt?: string | null; meta?: { title?: string | null; description?: string | null; image?: SeoUploadValue; canonicalUrl?: string | null; noIndex?: boolean | null; noFollow?: boolean | null; noSnippet?: boolean | null; } | null; }; ``` **Exported from:** `@nexload-sdk/seo` A collection document as Payload REST returns it (depth=1). [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L94) ### `SeoUploadValue` ```ts type SeoUploadValue = | { url?: string | null; alt?: string | null; width?: number | null; height?: number | null } | string | number | null | undefined; ``` **Exported from:** `@nexload-sdk/seo` Upload value as Payload REST returns it at depth=1, or an unpopulated id. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/seo/src/types.ts#L52) ## Entrypoints and Runtime Constraints * **Module format:** ESM only (`"type": "module"`). * **`@nexload-sdk/seo`:** Universal (Node.js and browser). Never imports `next`, `payload`, or any `@payloadcms/*` package. * **`@nexload-sdk/seo/next`:** Runs in Next.js 16 App Router (`next >=16.0.0 <17.0.0`). Never imports `payload` or any `@payloadcms/*` package. * **`@nexload-sdk/seo/payload`:** Runs in Node.js on the Payload CMS server (`payload >=3.85.0 <4.0.0`, `@payloadcms/plugin-seo >=3.85.0 <4.0.0`). Never imports `next`. * **`@nexload-sdk/seo/payload/admin.css`:** Payload Admin UI stylesheet for bidirectional/RTL search preview rules (`.nexload-seo-meta`). ## Logging Events Structured logs use `@nexload-sdk/logger` child loggers (`{ module: "seo-next" }` in `@nexload-sdk/seo/next`, `{ module: "payload-seo" }` in `@nexload-sdk/seo/payload`): | Event | Level | Where | Meaning | | --- | --- | --- | --- | | `seo.sitemap.source_failed` | `warn` | `createSitemap` | One sitemap source threw or exceeded `1,000` pages; remaining sources still emit | | `seo.sitemap.size_warning` | `warn` | `createSitemap` | Total sitemap entries reached `45,000` | | `seo.schema.offer_skipped` | `warn` | `resolveSeo` | Product `Offer` omitted from JSON-LD due to invalid or negative price | | `seo.redirect.written` | `info` | `nexloadSeo` | Automatic reference redirect row created on published path change | | `seo.redirect.preserved` | `info` | `nexloadSeo` | Existing redirect row kept untouched on published path change | --- # Production Guides & Recipes CMS setup, endpoints, Next.js metadata and JSON-LD, sitemap, robots, redirects, Persian URLs, and limits. **Topic:** guides **Package:** `@nexload-sdk/seo` v1.0.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/seo/guides/ ## CMS setup Add `nexloadSeo` to your existing Payload config: set `serverURL: process.env.CMS_PUBLIC_URL` so upload `url` values are absolute (otherwise relative upload URLs resolve against the storefront origin). Configure `@payloadcms/plugin-redirects` **before** `nexloadSeo` when `redirects: true`, include every SEO collection in its `collections` array, require `alt` on your uploads collection, enable database transactions on your adapter, and restrict `settingsAccess.update` to an explicit permission—any signed-in user must not change site-wide indexing. Anonymous readers only see published documents, including through Payload's built-in REST API. Only admins can create accounts or assign roles: ```ts // src/payload.config.ts import { postgresAdapter } from "@payloadcms/db-postgres"; import { redirectsPlugin } from "@payloadcms/plugin-redirects"; import { nexloadSeo } from "@nexload-sdk/seo/payload"; import { buildConfig } from "payload"; import type { Access, FieldAccess, PayloadRequest } from "payload"; // src/modules/seo/index.ts re-exports seoEndpoints from ./seo.endpoint import { seoEndpoints } from "./modules/seo"; const hasRole = (req: PayloadRequest, role: "admin" | "seo") => Array.isArray(req.user?.roles) && (req.user.roles as string[]).includes(role); const isAdmin: Access = ({ req }) => hasRole(req, "admin"); const isAdminField: FieldAccess = ({ req }) => hasRole(req, "admin"); const isAdminOrSelf: Access = ({ req }) => hasRole(req, "admin") || (req.user ? { id: { equals: req.user.id } } : false); export default buildConfig({ secret: process.env.PAYLOAD_SECRET!, serverURL: process.env.CMS_PUBLIC_URL, db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! }, }), collections: [ { slug: "users", auth: true, access: { create: isAdmin, update: isAdminOrSelf, delete: isAdmin, read: isAdminOrSelf, }, fields: [ { name: "roles", type: "select", hasMany: true, options: ["admin", "seo"], saveToJWT: true, access: { create: isAdminField, update: isAdminField, }, }, ], }, { slug: "media", upload: true, access: { read: () => true }, fields: [{ name: "alt", type: "text", required: true }], }, { slug: "posts", versions: { drafts: true }, access: { read: ({ req }) => (req.user ? true : { _status: { equals: "published" } }), }, fields: [ { name: "title", type: "text" }, { name: "slug", type: "text", required: true, unique: true, index: true, validate: (value: unknown) => (typeof value === "string" && /^[^\s%/?#]+$/u.test(value)) || "Slug must not contain spaces, %, /, ? or #", }, { name: "content", type: "textarea" }, ], }, ], endpoints: seoEndpoints, plugins: [ redirectsPlugin({ collections: ["posts"], }), nexloadSeo({ siteUrl: "https://example.com", uploadsCollection: "media", redirects: true, sitemapSources: ["posts"], settingsAccess: { update: ({ req }) => hasRole(req, "admin") || hasRole(req, "seo"), }, collections: { posts: { freshness: ["title", "content"], path: (doc) => `/blog/${doc.slug ?? ""}`, }, }, }), ], }); ``` Import the admin stylesheet in your Payload admin CSS file so the `@payloadcms/plugin-seo` search preview renders RTL/LTR text correctly: ```css @import "@nexload-sdk/seo/payload/admin.css"; ``` Keep `settingsAccess.read` public (the default). The settings endpoint reads anonymously; restricting read access breaks pages, sitemap, and robots. Slugs are stored decoded so the route lookup and sitemap agree. ## CMS endpoints (you own these) This package ships no HTTP endpoints; your Payload CMS must expose `/api/seo/route`, `/api/seo/settings`, and `/api/seo/sitemap/:source` as public JSON (for example from `src/modules/seo/seo.endpoint.ts`). Payload's Local API defaults to `overrideAccess: true`, which would leak restricted documents, so every content read below passes `overrideAccess: false` with no user and filters draft collections to published documents (`draft: false` and `_status: { equals: "published" }`). Denied reads in the route endpoint pass `disableErrors: true` so a null or empty result returns `{ kind: "missing" }`. In the sitemap endpoint, keep errors enabled because a failing source is isolated by `createSitemap`. Redirect rows may be read with `overrideAccess: true`, provided the redirect target is re-read with `overrideAccess: false` and verified published (otherwise return `{ kind: "missing" }`). Mapping happens on the CMS side so the endpoint owns the `path` rule and the Next.js app never calls `getPayload`. Run `payload generate:types` for typed documents. ```ts // src/modules/seo/seo.endpoint.ts import { toRedirectKey, toSeoDocument } from "@nexload-sdk/seo"; import type { Endpoint } from "payload"; function safeDecodeSegment(segment: string): string { try { return decodeURIComponent(segment); } catch { return segment; } } const pathForPost = (doc: Record) => `/blog/${String(doc.slug ?? "")}`; export const seoEndpoints: Endpoint[] = [ { path: "/seo/route", method: "get", handler: async (req) => { const rawPath = req.searchParams.get("path") ?? "/"; const requestPath = rawPath.startsWith("/") ? rawPath : `/${rawPath}`; const lastSegment = requestPath.split("/").filter(Boolean).at(-1); if (lastSegment) { const slug = safeDecodeSegment(lastSegment); const posts = await req.payload.find({ collection: "posts", where: { and: [{ slug: { equals: slug } }, { _status: { equals: "published" } }], }, draft: false, depth: 1, limit: 1, overrideAccess: false, disableErrors: true, }); const doc = posts?.docs?.[0]; if (doc && toRedirectKey(pathForPost(doc)) === toRedirectKey(requestPath)) { return Response.json({ kind: "page", page: toSeoDocument(doc, { path: pathForPost(doc) }), }); } } const redirects = await req.payload.find({ collection: "redirects", where: { from: { equals: toRedirectKey(requestPath) } }, depth: 0, limit: 1, overrideAccess: true, }); const row = redirects.docs[0]; const ref = row?.to?.reference; if (row?.to?.type === "reference" && ref?.relationTo === "posts" && ref.value) { const targetId = typeof ref.value === "object" ? ref.value.id : ref.value; const targets = await req.payload.find({ collection: "posts", where: { and: [{ id: { equals: targetId } }, { _status: { equals: "published" } }], }, draft: false, depth: 0, limit: 1, overrideAccess: false, disableErrors: true, }); const target = targets?.docs?.[0]; if (target?.slug) { return Response.json({ kind: "redirect", location: pathForPost(target), }); } } return Response.json({ kind: "missing" }); }, }, { path: "/seo/settings", method: "get", handler: async (req) => { const settings = await req.payload.findGlobal({ slug: "seo-settings", depth: 1, overrideAccess: false, }); return Response.json(settings); }, }, { path: "/seo/sitemap/:source", method: "get", handler: async (req) => { if (req.routeParams?.source !== "posts") { return Response.json({ error: "Unknown sitemap source" }, { status: 404 }); } const pageParam = Number(req.searchParams.get("page") ?? "1"); const page = Number.isFinite(pageParam) && pageParam >= 1 ? Math.floor(pageParam) : 1; const posts = await req.payload.find({ collection: "posts", where: { _status: { equals: "published" } }, draft: false, depth: 1, limit: 100, page, overrideAccess: false, }); return Response.json({ docs: posts.docs.map((doc) => toSeoDocument(doc, { path: pathForPost(doc) })), hasNextPage: posts.hasNextPage, }); }, }, ]; ``` Collections without drafts have no `_status` field, so omit the `_status` filter for those collections. If a collection uses `name` instead of `title`, pass `{ ...doc, title: doc.name }` to `toSeoDocument`. ## Next.js page metadata and JSON-LD Always check `res.ok` and throw before parsing instead of passing an error body to `toSeoSite`, because failing open would re-enable indexing. ```tsx // app/[...path]/page.tsx import type { Metadata } from "next"; import { notFound } from "next/navigation"; import { toSeoSite, type SeoRoute, type SeoSettingsDoc } from "@nexload-sdk/seo"; import { resolveSeo } from "@nexload-sdk/seo/next"; async function getSeoRoute(path: string): Promise { const res = await fetch(`${process.env.CMS_URL}/api/seo/route?path=${encodeURIComponent(path)}`, { cache: "no-store", }); if (!res.ok) throw new Error(`Failed to fetch SEO route: ${res.status}`); return (await res.json()) as SeoRoute; } async function getSeoSettings(): Promise { const res = await fetch(`${process.env.CMS_URL}/api/seo/settings`, { cache: "no-store" }); if (!res.ok) throw new Error(`Failed to fetch SEO settings: ${res.status}`); return (await res.json()) as SeoSettingsDoc; } export async function generateMetadata({ params, }: { params: Promise<{ path: string[] }>; }): Promise { const { path: segments } = await params; const route = await getSeoRoute(`/${segments.join("/")}`); if (route.kind !== "page") return {}; const site = toSeoSite(await getSeoSettings(), { url: process.env.SITE_URL! }); return resolveSeo(route.page, site).metadata; } export default async function Page({ params }: { params: Promise<{ path: string[] }> }) { const { path: segments } = await params; const route = await getSeoRoute(`/${segments.join("/")}`); if (route.kind !== "page") notFound(); const site = toSeoSite(await getSeoSettings(), { url: process.env.SITE_URL! }); const { jsonLd } = resolveSeo(route.page, site); return (

{route.page.title}

{jsonLd ? (