Production Guides & Recipes
CMS setup
Section titled “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:
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.endpointimport { 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:
@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)
Section titled “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.
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<string, unknown>) => `/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
Section titled “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.
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<SeoRoute> { 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<SeoSettingsDoc> { 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<Metadata> { 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 ( <main> <h1>{route.page.title}</h1> {jsonLd ? ( <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLd }} /> ) : null} </main> );}resolveSeo sets title: { absolute } once from seo-settings (do not add another title: { template } in a parent layout). For product entities, pass price: { amount, unit: "IRT" | "IRR" } using a safe integer; resolveSeo converts to IRR via convertMoney and emits Offer (or logs seo.schema.offer_skipped and omits the Offer on invalid/negative prices). jsonLd is escaped for safe inline <script> rendering and is null when the page is noIndex or non-self-canonical.
Sitemap
Section titled “Sitemap”Use dynamic = "force-dynamic" and cache: "no-store" so Next.js does not prerender stale output; consumers that cache must revalidate sitemap and robots on publish, unpublish, and settings changes.
import type { MetadataRoute } from "next";import { toSeoSite, type SeoDocument, type SeoSettingsDoc } from "@nexload-sdk/seo";import { createSitemap } from "@nexload-sdk/seo/next";
export const dynamic = "force-dynamic";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> { const settingsRes = await fetch(`${process.env.CMS_URL}/api/seo/settings`, { cache: "no-store" }); if (!settingsRes.ok) throw new Error(`Failed to fetch SEO settings: ${settingsRes.status}`); const settings = (await settingsRes.json()) as SeoSettingsDoc; const site = toSeoSite(settings, { url: process.env.SITE_URL! });
const generate = createSitemap({ site, sources: { posts: async (page) => { const res = await fetch(`${process.env.CMS_URL}/api/seo/sitemap/posts?page=${page}`, { cache: "no-store", }); if (!res.ok) throw new Error(`Sitemap source failed: ${res.status}`); return (await res.json()) as { docs: SeoDocument[]; hasNextPage: boolean }; }, }, });
return generate();}createSitemap paginates every source starting at page = 1, isolates failing sources (logging seo.sitemap.source_failed and throwing only if all configured sources fail), stops any source after 1,000 pages, logs seo.sitemap.size_warning at 45,000 entries, and escapes XML-sensitive characters in URLs.
Robots and AI crawler presets
Section titled “Robots and AI crawler presets”import type { MetadataRoute } from "next";import { toSeoSite, type SeoSettingsDoc } from "@nexload-sdk/seo";import { createRobots } from "@nexload-sdk/seo/next";
export const dynamic = "force-dynamic";
export default async function robots(): Promise<MetadataRoute.Robots> { const settingsRes = await fetch(`${process.env.CMS_URL}/api/seo/settings`, { cache: "no-store" }); if (!settingsRes.ok) throw new Error(`Failed to fetch SEO settings: ${settingsRes.status}`); const settings = (await settingsRes.json()) as SeoSettingsDoc; const site = toSeoSite(settings, { url: process.env.SITE_URL! });
return createRobots({ site });}Static disallow passed to createRobots({ site, disallow }) merges as a union with the seo-settings disallow list.
| Preset | Search agents (OAI-SearchBot, Claude-SearchBot, PerplexityBot) | Training agents (GPTBot, ClaudeBot, Google-Extended, Applebot-Extended, CCBot) |
|---|---|---|
allow-all | Allowed (follows * baseline disallows) | Allowed (follows * baseline disallows) |
search-only (default) | Allowed (follows * baseline disallows) | Disallowed (Disallow: /) |
block-all-ai | Disallowed (Disallow: /) | Disallowed (Disallow: /) |
Custom robots.rules entries cannot re-open an agent blocked by the active preset.
Redirects and route lookup (proxy.ts)
Section titled “Redirects and route lookup (proxy.ts)”On the CMS/API side, check live published routes first, then normalize unknown paths with toRedirectKey(path) to query the redirects collection. On the Next.js side, issue a 308 permanent redirect with Cache-Control: no-store from proxy.ts, and scope config.matcher to CMS-backed routes only:
import { NextResponse, type NextRequest } from "next/server";import type { SeoRoute } from "@nexload-sdk/seo";
export async function proxy(request: NextRequest) { const res = await fetch( `${process.env.CMS_URL}/api/seo/route?path=${encodeURIComponent(request.nextUrl.pathname)}`, { cache: "no-store" }, ); if (!res.ok) return NextResponse.next();
const route = (await res.json()) as SeoRoute; if (route.kind === "redirect") { const response = NextResponse.redirect(new URL(route.location, request.url), 308); response.headers.set("Cache-Control", "no-store"); return response; }
return NextResponse.next();}
export const config = { matcher: ["/blog/:path*"],};When redirects: true, nexloadSeo ignores drafts and autosaves and records a reference redirect row in the same database transaction when a published document’s path changes.
Indexing vs crawling
Section titled “Indexing vs crawling”seo-settings.general.indexing(defaulttrue): controls search engine indexing. Whenfalse,resolveSeoemitsrobots: { index: false, ... }and returnsjsonLd: null,createSitemapreturns[], andcreateRobotsomits thesitemapURL.- Document
meta.noIndex/meta.noFollow/meta.noSnippet: per-page overrides.resolveSeosetsmax-image-preview: "large"by default andnosnippet: truewhenmeta.noSnippetis enabled. Non-indexable or non-self-canonical documents are excluded from the sitemap and JSON-LD. seo-settings.robots: controlsrobots.txtcrawler rules independently ofindexing. Do not useDisallowto deindex a section; setnoIndexon the documents (orrobots: { index: false }in Next.js layoutmetadatafor non-CMS sections) so crawlers can still read thenoindexdirective.
Cache ownership
Section titled “Cache ownership”The consumer owns HTTP reads, route lookup, and cache invalidation. When a document is published, unpublished, or renamed—or when seo-settings or a redirects row changes—invalidate:
- The current document path and any historical/redirected paths
/sitemap.xmland/robots.txt- Cached
seo-settingsreads
Pair with @nexload-sdk/payload-revalidate for transaction-safe cache invalidation.
Persian URLs
Section titled “Persian URLs”Pass raw paths (/blog/سلام), already percent-encoded paths (/blog/%D8%B3%D9%84%D8%A7%D9%85), or paths containing literal percents (/off/100%25) without pre-encoding them yourself. The package encodes each segment once into a single-encoded canonical URL and drops fragments. Always normalize redirect lookups with toRedirectKey(pathname).
The plugin does not normalize slugs itself; configure a unique, required slug field on SEO collections (for Persian slugs, pair with @nexload-sdk/persian or @nexload-sdk/payload-fields).
Limits
Section titled “Limits”- Transactions & redirects: Automatic redirects require database transactions: without them, a public write that changes the document path is rejected (other edits still save);
@payloadcms/plugin-redirectsmust be configured beforenexloadSeoand itscollectionsmust include every SEO collection. - Not supported in v1 (startup error): Payload content localization (
config.localization),experimental.localizeStatus, auth collections, an existingseo-settingsglobal, an existing top-levelmeta,publishedAtorcontentUpdatedAtfield. - Known limitations:
- Two concurrent renames of the same document can record only one redirect (no row locking).
- Local API
payload.restoreVersion({ draft: true })in Payload 3.86 drops the draft flag and publishes. - Unpublish then republish at a new path needs a manual redirect.
- Single sitemap file (sitemaps allow at most
50,000URLs;createSitemapwarns at45,000, does not split, and stops any source after1,000pages). Split larger sites into several sitemap routes/sources yourself. - Next.js 16 writes sitemap URLs into XML unescaped, so the package escapes them (
&,<,>,",').
- Admin CSS: Import
@nexload-sdk/seo/payload/admin.cssfrom the Payload admin stylesheet.