gecut

seo

by gecut
nexload-sdk
SEO & metadata
v3
>=3.85.0 <4.0.0
MIT

Overview

Summary generated from the README

Wraps the Payload SEO plugin to add meta fields, an seo-settings global, Persian labels, publish and content-update timestamps, and optional automatic redirects when a published path changes. A companion Next.js entry resolves metadata and JSON-LD, and generates sitemaps and robots rules including AI crawler presets. It requires Payload 3.85 or later, the Payload SEO plugin and Next.js 16, and you write the public SEO endpoints yourself.

Features

  • nexloadSeo plugin adds meta fields and an seo-settings global to chosen collections
  • Automatic redirect rows created when a published document path changes
  • resolveSeo builds Next.js metadata and JSON-LD from a document and site settings
  • createSitemap and createRobots with indexing switch and AI crawler presets
  • Portable contracts and mappers for SEO site, document and route data
  • RTL-aware admin stylesheet for the search preview

Use cases

  • Add per-page SEO metadata, sitemap and robots output to a Payload and Next.js site
  • Keep old URLs working with 308 redirects after editors rename published slugs
  • Control AI crawler access and site-wide indexing from the Payload admin

From the author

SEO contracts, Next.js metadata/sitemap/robots and a Payload CMS SEO plugin.

Installation

npm i @nexload-sdk/seo

3

Stars

0

Forks

0

Open Issues

Today

Last Updated

284

Weekly Downloads

v1.0.0

npm Version

237.0 KB

Unpacked Size

2

Dependencies

Repository stars

3+2 since Sep 6

Show data
Repository stars by day (UTC)
DateStars
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20262
Nov 16, 20262
Nov 15, 20262
Nov 14, 20262
Nov 13, 20262
Nov 12, 20262
Nov 11, 20262
Nov 10, 20262
Nov 9, 20262
Nov 8, 20262
Nov 7, 20262
Nov 6, 20262
Nov 5, 20262
Nov 4, 20262
Nov 3, 20262
Nov 2, 20262
Nov 1, 20262
Oct 31, 20262
Oct 30, 20262
Oct 29, 20262
Oct 28, 20262
Oct 27, 20262
Oct 26, 20262
Oct 25, 20262
Oct 24, 20262
Oct 23, 20262
Oct 22, 20262
Oct 21, 20262
Oct 20, 20262
Oct 19, 20262
Oct 18, 20262
Oct 17, 20261
Oct 16, 20261
Oct 15, 20261
Oct 14, 20261
Oct 13, 20261
Oct 12, 20261
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20261
Oct 5, 20261
Oct 4, 20261
Oct 3, 20261
Oct 2, 20261
Oct 1, 20261
Sep 30, 20261
Sep 29, 20261
Sep 28, 20261
Sep 27, 20261
Sep 26, 20261
Sep 25, 20261
Sep 24, 20261
Sep 23, 20261
Sep 22, 20261
Sep 21, 20261
Sep 20, 20261
Sep 19, 20261
Sep 18, 20261
Sep 17, 20261
Sep 16, 20261
Sep 15, 20261
Sep 14, 20261
Sep 13, 20261
Sep 12, 20261
Sep 11, 20261
Sep 10, 20261
Sep 9, 20261
Sep 8, 20261
Sep 7, 20261
Sep 6, 20261

Shared by 8 plugins in gecut/nexload-sdk.

npm weekly downloads

Trends appear after 7 days of data. Collecting since Dec 4 — 2 daily snapshots so far.

Each point is npm's rolling 7-day download count.

Health Score

75/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1086380959-seo.svg)](https://payloaddirectory.dev/plugins/1086380959-seo)
HTML
<a href="https://payloaddirectory.dev/plugins/1086380959-seo"><img src="https://payloaddirectory.dev/badge/1086380959-seo.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Oct 30, 2025Published Dec 3, 2026

README

@nexload-sdk/seo

SEO contracts, Next.js metadata/sitemap/robots helpers, and a Payload CMS SEO plugin.

Install

pnpm add @nexload-sdk/seo

Install the optional peer dependencies required by the entry points you use:

  • @nexload-sdk/seo/next: next (>=16.0.0 <17.0.0)
  • @nexload-sdk/seo/payload: payload (>=3.85.0 <4.0.0) and @payloadcms/plugin-seo (>=3.85.0 <4.0.0)
  • Automatic redirects (redirects: true): @payloadcms/plugin-redirects (configured before nexloadSeo)

Entries

EntryRuntimePeersPurpose
@nexload-sdk/seoUniversal (Node / Browser)NonePortable JSON contracts (SeoSite, SeoDocument, SeoRoute) and pure mappers (toSeoSite, toSeoDocument, toRedirectKey)
@nexload-sdk/seo/nextNext.js App RouternextresolveSeo, createSitemap, createRobots
@nexload-sdk/seo/payloadNode.js / Payload CMSpayload, @payloadcms/plugin-seonexloadSeo plugin (meta fields, seo-settings global, Persian labels, publishedAt/contentUpdatedAt, automatic redirects)
@nexload-sdk/seo/payload/admin.cssPayload Admin UIpayloadBidirectional/RTL search preview rules (.nexload-seo-meta)

CMS setup

Add 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, 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:

// 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:

@import "@nexload-sdk/seo/payload/admin.css";

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.

// 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<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,
      });
    },
  },
];

Web setup

Metadata and JSON-LD (app/[...path]/page.tsx)

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>
  );
}

Sitemap (app/sitemap.ts)

Use dynamic = "force-dynamic" and cache: "no-store" so Next.js does not prerender stale output; consumers that cache must revalidate sitemap/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();
}

Robots (app/robots.ts)

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 });
}

Route lookup and 308 redirects (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*"],
};

Indexing vs crawling

  • seo-settings.general.indexing (default true): controls search engine indexing. When false, resolveSeo emits robots: { index: false, ... } and returns jsonLd: null, createSitemap returns [], and createRobots omits the sitemap URL.
  • Document meta.noIndex / meta.noFollow / meta.noSnippet: per-page overrides. resolveSeo sets max-image-preview: "large" by default and nosnippet: true when meta.noSnippet is enabled. Non-indexable or non-self-canonical documents are excluded from the sitemap and JSON-LD.
  • seo-settings.robots: controls robots.txt crawler rules independently of indexing.

AI crawler presets

PresetSearch agents (OAI-SearchBot, Claude-SearchBot, PerplexityBot)Training agents (GPTBot, ClaudeBot, Google-Extended, Applebot-Extended, CCBot)
allow-allAllowed (follows * baseline disallows)Allowed (follows * baseline disallows)
search-only (default)Allowed (follows * baseline disallows)Disallowed (Disallow: /)
block-all-aiDisallowed (Disallow: /)Disallowed (Disallow: /)

Custom robots.rules entries cannot re-open an agent blocked by the active preset.

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.xml and /robots.txt
  • Cached seo-settings reads

Pair with @nexload-sdk/payload-revalidate for transaction-safe cache invalidation.

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-redirects must be configured before nexloadSeo and its collections must include every SEO collection.
  • Not supported in v1 (startup error): Payload content localization (config.localization), experimental.localizeStatus, auth collections, an existing seo-settings global, an existing top-level meta, publishedAt or contentUpdatedAt field.
  • 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,000 URLs; createSitemap warns at 45,000, does not split, and stops any source after 1,000 pages). 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.css from the Payload admin stylesheet.

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):

EventLevelWhereMeaning
seo.sitemap.source_failedwarncreateSitemapOne sitemap source threw or exceeded 1,000 pages; remaining sources still emit
seo.sitemap.size_warningwarncreateSitemapTotal sitemap entries reached 45,000
seo.schema.offer_skippedwarnresolveSeoProduct Offer omitted from JSON-LD due to invalid or negative price
seo.redirect.writteninfonexloadSeoAutomatic reference redirect row created on published path change
seo.redirect.preservedinfonexloadSeoExisting redirect row kept untouched on published path change

Agent skills

This package ships agent skills that match its version. After install they are at node_modules/@nexload-sdk/seo/skills/:

  • seo — skills/seo/SKILL.md

Point your coding agent at them from AGENTS.md, or install from the repository with npx skills add gecut/nexload-sdk --skill <name>.

Similar plugins