Chris1415 avatar

sitecore-content-sdk-nextjs-app-router

Content SDK skills for Next.js App Router head apps, including Content SDK Atoms (BETA). Install with 'Sitecore Content SDK - Core'.

version
0.13.0
GitHub stars
12

Install

/plugin install sitecore-content-sdk-nextjs-app-router@sitecore-skills-pocs

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Chris1415/sitecore-skills-pocs.

Contents

Discovered from source

Skills 17

Create a Content SDK atom (App Router) — BETA

An atom is a coded, governed building block that marketers (or Design Studio's AI) compose into low-code components without a deploy ([UNVERIFIED]: Design Studio was never seen offering this; see content-sdk-app-router-atoms § 9). You write the atom once; every component built from it is content. This skill covers writing one. Wiring atoms into an app, the runtime and its traps live in content-sdk-app-router-atoms; run its version gate first.

1. Is it an atom?

The thing…Make it
renders one authored value (text, rich text, image, link, date, file)leaf atom, bound through a field schema
arranges other atoms (stack, grid, columns, card shell)container atom with slots
has a closed set of looks (size, tone, emphasis)one atom with an enum prop, never one atom per look
fetches data, holds state across interactions, reads useSitecore, renders a list of datasource children, personalizescode component, not an atom (content-sdk-app-router-component-scaffold)
is a whole section (hero, card, CTA band)not an atom: compose it as a Document from atoms

Keep the set small. A catalog of 8–15 atoms covers most marketing pages; every atom is API surface you version forever (§ 6).

2. Anatomy (Content Kit convention)

src/components/atoms/<name>/<name>.schema.ts   catalog definition (Zod) + props type
src/components/atoms/<name>/<name>.tsx         React renderer
src/atoms/catalog.ts                           defineAtomsCatalog: one entry per atom key
src/atoms/registry.tsx                         defineAtomsRegistry ('use client'): key → renderer
src/atoms/index.ts                             the ONE entry the CLI and bundler read

src/components/atoms/** and **/*.schema.ts must be in componentMap.exclude, or the folder is registered as renderings (content-sdk-component-naming-traps).

3. The schema

import { textFieldSchema, withPropMeta } from "@sitecore-content-sdk/nextjs/atoms";
import { z } from "zod";

export const calloutCatalogDefinition = {
  props: z.object({
    text: textFieldSchema().describe("Single-Line Text field shown as the callout."),
    tone: withPropMeta(z.enum(["info", "success", "warning"]).default("info").describe("Colour role."), { control: "select" }),
    className: z.string().optional().describe("Optional extra classes."),
  }),
  description: "Category: Content. Short highlighted statement with a semantic tone.",
  example: { text: { value: "Free shipping over €50" }, tone: "info" },
  slots: [],          // leaf; a container declares ["default"]
  version: "1.0.0",
};
export type CalloutProps = z.infer<typeof calloutCatalogDefinition.props>;

Rules:

  • Authored content goes through a field schema (textFieldSchema, richTextFieldSchema, imageFieldSchema, linkFieldSchema, dateFieldSchema, fileFieldSchema). A Document binds it with {"$state": "/fields/<Field>"} and gets the field object {value}. There is no number, checkbox or multiline schema: use textFieldSchema() or a plain Zod prop.
  • Design decisions are enums, not free strings. gap: "sm" | "md" | "lg" maps to your spacing scale; a free gap: string lets every composer invent one. Keep className as the single escape hatch.
  • description and example are the AI's brief. They are serialized with the props as JSON Schema; that Design Studio's generator and catalog panel read them is [UNVERIFIED]. Start description with Category: <X>., state when to use the atom, and what it is not.
  • withPropMeta(schema, { control }) is meant as a Design Studio editor hint (select, text, checkbox, …), [UNVERIFIED] in Design Studio itself. The control vocabulary is not documented; select / text / checkbox are what Sitecore's own atoms use.
  • Defaults live in Zod (.default()), so a Document can omit them.
  • allowedChildren / allowedParents are hints only; the runtime does not enforce them.

4. The renderer

import { cn } from "@/lib/atoms-utils";
import type { CalloutProps } from "./callout.schema";

const TONE = { info: "bg-sky-50 text-sky-900", success: "bg-emerald-50 text-emerald-900", warning: "bg-amber-50 text-amber-900" } as const;

export function Callout({ text, tone = "info", className }: Partial<CalloutProps>) {
  const value = text?.value;
  if (value === undefined || value === "") return null;   // empty field renders nothing
  return <p data-slot="callout" className={cn("rounded-lg px-4 py-2", TONE[tone], className)}>{String(value)}</p>;
}
  • It is a client component. Atoms render inside the SDK's 'use client' wrapper: no async, no server-only imports, no data fetching. Hooks are allowed but are a smell (§ 1).
  • Every internal class must be a literal string in src/. Only Document className tokens are compiled at runtime; the atom's own classes reach the page through the build-time Tailwind scan. A class built by concatenation (`gap-${n}`) is never emitted. Use a lookup object.
  • Handle the empty field. Return null (or a placeholder in editing) rather than an empty tag.
  • Render values safely. Prefer the SDK field components (Text, RichText, Image, Link) when the value shape fits; dangerouslySetInnerHTML on a Single-Line Text value (as Content Kit's Heading does) trusts whatever an author types.
  • Use data-slot="<name>" on the root, as Sitecore's atoms do; tests and audits select by it.

Container atoms

Declare slots: ["default"] in the schema and render children:

// registry.tsx
Stack: ({ props, children }) => <Stack {...props}>{children}</Stack>,

A Document lists the children by element id: {"type": "Stack", "props": {...}, "children": ["title", "cta"]}. Named slots arrive as slots in the renderer props. Content Kit ships no container atom; a Stack (direction, gap, align, justify, padding, wrap as enums) is the first atom to write.

5. Register and lock

  1. catalog.ts: import the definition, add Callout: calloutCatalogDefinition under components. Keep stylingSolution: "tailwind" and actions: {}.
  2. registry.tsx: add Callout: ({ props }) => <Callout {...props} />. Keys must match the catalog exactly.
  3. Export the definition from src/components/atoms/index.ts (barrel).
  4. npm run sitecore-tools:atoms:update, then commit .sitecore/atoms.lock.json with the atom.
  5. CI: node <atoms skill>/scripts/check-atoms-lock.mjs --app . --fail-on-hash-blind. atoms validate exits 0 on an out-of-date lock (re-measured 2026-10-29: IV-010 printed, exit 0).

6. Changing an atom later

ChangeLock signalWhat to do
Add an optional prop or enum valueIV-010atoms update. Existing Documents keep working
Tighten Zod (.min, .max, .regex), edit .describe() / withPropMetanone (hash-blind)bump the atom's version, then atoms update (IV-009)
Rename or retype a prop, remove an enum valueIV-010 onlyBreaking. Every Document using it renders wrong or crashes. Add a new key (CalloutV2) instead
Retire the atom—legacy: true + atoms update. Design Studio stops offering it ([UNVERIFIED]); old Documents still render
Delete the atomMV-013Only after no Document references it. A missing renderer is a silent null render

The scaffold's bundled atoms-maintain skill (under .agents/skills/) says "delete, then update"; do not follow it while Documents may still use the atom.

7. Prove it (no tenant needed)

  1. Write a fixture folder with routes.json (renderings carrying params.ComponentRef and fields) and documents.json (one Document per ref, using the new atom).
  2. node scripts/mock-edge.mjs --dir <fixtures> --site <site>.
  3. .env.local: SITECORE_EDGE_PLATFORM_HOSTNAME and NEXT_PUBLIC_SITECORE_EDGE_PLATFORM_HOSTNAME = http://127.0.0.1:4599, any context id, GENERATE_STATIC_PATHS=false.
  4. npm run build && npx next start -p 3301, never next dev.
  5. Assert: data-slot="<name>" present per expected instance; every Document class in the page's <style>; the atom's own classes in the build CSS; an empty field renders nothing.
  6. Keep the fixture folder outside src/ (Tailwind would otherwise compile the Document classes at build time and hide a runtime-compiler failure).

Document shape: { "name": "...", "root": "<id>", "elements": { "<id>": { "type": "<AtomKey>", "props": {...}, "children": ["<id>", ...] } } }. The rendering's fields and params are injected as state; anything a Document stores in state.fields is overwritten.

8. Checklist

  • § 1 says atom, not component
  • Authored values use field schemas; design choices are enums; className is the only free string
  • description starts with Category:; example is valid against the schema
  • Renderer: client-safe, literal classes, empty-field null, data-slot
  • Catalog key = registry key; barrel export; excluded from componentMap
  • Lock updated and committed; CI gate green
  • Rendered in a Document via the mock MMS, next build && next start

Content SDK Atoms (App Router) — BETA

BETA, pre-GA, thinly documented by Sitecore. Mostly measured on stamp …20261021204512 (2026-10-29); capabilities, Container and Design Studio facts are from 2026-11-05; tenant facts from …20260930142740 (2026-10-02). It churns between builds. Re-run the version gate before trusting any line below. Items marked [UNVERIFIED] were not reachable on the test tenant.

1. Version gate (hard rule, run first)

npm view @sitecore-content-sdk/nextjs dist-tags   # measured on …20261021204512 and …20261104151713
  • Atoms exist only under the beta.atoms dist-tag.
    • It is not in latest (2.5.0) or canary (3.0.0-canary): neither has an atoms export in npm view on 2026-11-04, while beta.atoms does. Nor is it in beta.
    • beta is a stale July canary with no atoms. Never use it.
  • The tag moves often: it moved three times on 2026-11-04. On 2026-11-05 beta.atoms is 3.0.0-beta.atoms.20261104151713. Upgrading from 20261021204512 took the pins and § 4's generateMetadata line. Re-diff with content-sdk-upgrade-assistant for anything newer.
  • Exact pins only. The scaffold pins every @sitecore-content-sdk/* dependency to one stamp; the package lines differ (nextjs 3.0.0-, cli 2.4.0-, events/personalize/analytics-core 2.2.0-). A ^ range or a mixed stamp is unsupported.

Since 2026-10-21 the beta is stable 2.4.1 plus atoms, without the 2.5.0-canary items (references/version-matrix.md).

When NOT to use atoms:

  • Production with a support expectation, or a non-React host. The runtime is React only.
  • The nextjs-app-router-cache-components template. It returned HTTP 500 on every ComponentRef page (2026-10-02); the wrapper still does an uncached MMS fetch, so assume it still does until re-measured.
  • Components that must pass inline-editing checks. Pages editing inside atoms is [UNVERIFIED].
  • A component that fetches data, holds client state or renders a list over datasource children. Atoms are leaves plus layout; see content-sdk-atomic-design-assessment.
  • A production project without the user's explicit opt-in. Use a throwaway or playground workspace.

2. Decide: atom, code component or variant?

NeedUse
Marketers compose new components in Design Studio from governed primitives, without a deploy per componentAtoms + low-code (beta). Offered under Create component in Design Studio (§ 9)
Server data, ComponentQuery, GraphQL, custom data strategyCode component (content-sdk-app-router-component-scaffold)
Per-field inline editing an author must be able to useCode component with SDK field components
Start from Sitecore's reference atoms (Heading, Paragraph, Image, Number, Button, Container)Content Kit registry, fixed up after install (§ 4a). Leaf atoms field-bound since 2026-10-05
Write your own atom (a container, a token-governed variant)content-sdk-app-router-atom-create
New look for an existing renderingVariant (content-sdk-variants-vs-siblings)
GA support, non-React host, existing 2.4.0 appCode component

3. Mental model

  • An atom is code.
    • It is a Zod-typed entry in defineAtomsCatalog plus a React renderer in defineAtomsRegistry, built on @json-render/* 0.20.0.
    • It is registered only through SitecoreProvider atomsConfig, never in .sitecore/component-map*.
  • A low-code component is content: a json-render Document stored in "MMS".
    • The CM ships a rendering template Foundation/JavaScript Services/HostedJsonRendering (base Json Rendering) with a Single-Line Text field ComponentRef on the rendering definition item.
    • The Layout Service copies that field into rendering.params.ComponentRef (measured on Edge preview).
    • The Components API type: Hosted means "this rendering template".
    • The Document itself is not a CM item, so ser pull does not see it.
  • Render path. For each rendering, Placeholder → getComponentForRendering checks hidden / empty → then params.ComponentRef → then the component map → then the FEaaS / BYOC fallbacks. ComponentRef wins over everything.
    • A ComponentRef rendering goes to StudioComponentServerWrapper (async server component).
    • The wrapper picks a path, GET {edge}/mms/<path>, compiles the Document's Tailwind classes into a <style>, and renders the client StudioComponentWrapper → createNCC(doc) (no props since #654).
    • The wrapper builds state = {...doc.state, fields, params}: the rendering's fields and params overwrite any state.fields / state.params stored in the Document. Datasource fields bind with {"$state": "/fields/<Field>"}. The bound value is the field object {value}. That fits the field schemas; a plain-string prop needs "/fields/<Field>/value" (the object crashes the page, § 8).
    • The output is wrapped in <div class="component {params.styles}" id="{params.RenderingIdentifier}">.
    • Production does not validate Documents. validateAtomsDocument (#652) runs only on Design Studio previews; a malformed Document from MMS goes straight to createNCC.

Details, shapes and payloads: references/api-surface.md, references/design-studio-bridge.md.

4. Wiring (scaffold literally)

npx --yes create-content-sdk-app@2.5.0-beta.atoms.20261021204512 --yes --template nextjs-app-router --destination <dir>

Verify all of these exist; the stock steps are in the scaffold's own bundled atoms setup skill under .agents/skills/:

  • src/atoms/index.tsx (fixed path; the CLI accepts only index.ts or index.tsx)
  • exactly ONE of src/atoms/index.ts / index.tsx. Two means the lock validates one catalog and the runtime renders the other (§ 4a)
  • Providers.tsx atomsConfig={{ catalog, registry, navigate: router.push, compileCssAction: compileCssForDocumentAction }} and theming={scConfig.theming} (scaffolds older than 2026-10-05 lack the theming line, so live theme preview silently does nothing)
  • root instrumentation.ts → instrumentation-node.ts with await registerTailwindCssCompiler('src/app/globals.css')
  • next.config.ts serverExternalPackages: ['@tailwindcss/node']
  • zod ^4 and @tailwindcss/node ^4 as app dependencies
  • .gitignore .sitecore/* + !.sitecore/atoms.lock.json
  • From 20261104121033: generateMetadata({ appInputs: { [ATOMS_CATALOG_METADATA_KEY]: catalog } }) in sitecore.cli.config.ts, with the key from @sitecore-content-sdk/nextjs/atoms and catalog from src/atoms. An upgraded app without it still builds, with an empty catalog in its metadata (§ 9)

Template differences (all three beta templates scaffold src/atoms):

  • Pages Router (--template nextjs): no instrumentation, no serverExternalPackages and no compileCssAction. Atoms render server-side but unstyled; wire the compiler by hand if you need styles.
  • nextjs-app-router-cache-components: returns 500 on ComponentRef pages. Do not use.

4a. Content Kit (Sitecore shadcn registry)

https://content-kit.vercel.app/r/atoms.json is Sitecore's official shadcn registry (Apache-2.0): 5 field-bound leaf atoms (Heading, Paragraph, Image, Number, Button) and the Container layout atom, nothing else installable. The install still needs fixing up. Use only the recipe in references/content-kit.md. Measured 2026-10-29:

  • shadcn add rewrites the SDK pins to the registry's stamp as ^ ranges (2026-10-29: ^…20261006083839, cli down to ^2.3.0-…, a mixed stamp). Restore the exact pins right after (§ 1).
  • Without a components.json, imports land as "/lib/atoms-utils" (an absolute path). The docs say none is needed; add one, or fix the imports to @/lib/atoms-utils. The scaffold tsconfig also lacks the "@/*": ["src/*"] alias.
  • It writes src/atoms/index.ts next to the scaffold's index.tsx. The CLI and tsc read index.ts; the bundler reads index.tsx. Keep exactly one (delete the empty scaffold index.tsx).
  • Exclude 'src/components/atoms/**' and '**/*.schema.ts' from componentMap. The installer prints this; it does not do it.
  • scripts/check-atoms-lock.mjs fails on both layouts (two entry files, unexcluded atoms under src/components/).
  • Field-bound but not SDK-rendered. Heading expects the tag inside a Single-Line Text value (<h2>…</h2>); Heading and Paragraph render with dangerouslySetInnerHTML; Image is a plain <img>. Pages inline editing inside them is [UNVERIFIED].
  • Container is the Kit's only atom with children (slots: ["default"]). Free CSS strings, so a governed token Stack (content-sdk-app-router-atom-create) still has a place. Explicit-width columns ignore a nested Container with its own columns; fix in references/content-kit.md.
  • Adding one atom to an existing app: not r/atoms.json, which rewrites the catalog and registry. See references/content-kit.md.

MMS host. The wrapper calls resolveEdgeUrl() with no argument. It honours only the server env SITECORE_EDGE_PLATFORM_HOSTNAME, else https://edge-platform.sitecorecloud.io. A custom sitecore.config api.edge.edgeUrl or NEXT_PUBLIC_SITECORE_EDGE_PLATFORM_HOSTNAME moves layout but not MMS.

5. Catalog rules that bite

  • components and actions are both required (actions: {}). Exact<> rejects unknown keys at compile time only.
  • Set stylingSolution: 'tailwind' explicitly. The default is 'inline-css', whatever PR summaries say.
  • For Sitecore-bound props, use the field schemas: textFieldSchema, richTextFieldSchema, linkFieldSchema, imageFieldSchema, dateFieldSchema, fileFieldSchema. None exist for number, checkbox, multi-line text or reference fields.
  • Retire an atom with legacy: true, then run atoms update.
    • legacy is hashed (IV-010).
    • Never delete an atom that a Document still uses. The render goes null with only a console line.
    • This overrides the scaffold's bundled atoms maintain skill, which says delete.
  • Splitting the catalog across modules is fine as long as src/atoms/index.tsx re-exports catalog and registry (validated).
  • Keep atoms out of src/components/, or add the folder to componentMap.exclude in sitecore.cli.config.ts ('src/components/atoms/**'). Everything there is auto-registered as a rendering (content-sdk-component-naming-traps). Content Kit installs there by default; name clashes with src/components/ui/* then break the generated map at compile time.
  • Renaming the props of an existing atom key (e.g. the scaffold's Heading{text} → Content Kit's Heading{defaultValue}) raises only IV-010 and exits 0. Every Document using the old props renders wrong or crashes. Treat it as retire-and-add (new key), not replace.
  • allowedChildren / allowedParents are Design Studio hints. The runtime does not enforce them: a Paragraph inside a Button rendered <a><p><p>.

6. Lock file CI policy

sitecore-tools project atoms validate exits 0 on every lock issue (MV-012 "lock not found" included) unless atoms.validation.breakOnError is true. The exceptions are MV-010 (no src/atoms/index.ts(x)) and MV-011 (no catalog export): those throw and exit 1 regardless.

  • Run npm run sitecore-tools:atoms:update after an intentional change, and commit .sitecore/atoms.lock.json.
  • In CI, run node scripts/check-atoms-lock.mjs --app . --fail-on-hash-blind. It parses the codes and fails on any of them, whatever the config says. Alternatively pass -c <config> with a config that spreads the base and sets breakOnError: true.
  • The hash cannot see Zod check parameters (.min/.max/.regex…), .meta(), .describe(), withPropMeta, or the catalog's stylingSolution. Bump the atom's version by hand for those (that raises IV-009, and update accepts it). The script warns when such a line changed since the last lock commit without a version edit.
  • Hashed (IV-010): new props, types, enum values, defaults, description, allowedParents/Children, legacy.

Full code table: references/api-surface.md § CLI codes.

7. Runtime CSS

  • How it works. The compiler runs @tailwindcss/node against globals.css for the Document's className tokens. It emits only the used @layer theme tokens plus @layer utilities in a <style> next to the component.
    • Unresolvable classes are dropped from the CSS and stay in the markup.
    • The in-memory LRU holds 200 class sets and is lost on every cold start.
    • Measured locally: p50 about 11 ms per unique 30-class set.
  • No registered compiler → the Document renders unstyled, with no log line (debug only).
  • dark: compiles to prefers-color-scheme. With a class-driven 3-state theme, declare @custom-variant dark in globals.css (content-sdk-app-router-theme-hydration-pattern).
  • Atom-internal classes (cva variants, fixed layout classes) are not compiled at runtime. They reach the page only through the build-time stylesheet, because Tailwind scans src/**. An atom whose source lives outside the scanned tree (a package) renders unstyled unless you add an @source.
  • Installing the Blok theme (Content Kit) adds @custom-variant dark (&:is(.dark *)) to globals.css, which switches dark: to class-driven.
  • compileCssForDocumentAction is a public Server Action.
    • Its id ships in the client bundle, and an anonymous POST returns compiled CSS. Each new class set costs a compile.
    • It is only needed in Design Library editing. Rate-limit it or gate it on draft mode before exposing the app.
  • Vercel / editing-host viability (native oxide binary, file tracing of globals.css) is [UNVERIFIED]. The Windows lockfile does list @tailwindcss/oxide-linux-x64-gnu.

8. Debugging a low-code component that renders nothing

Run node scripts/probe-mms.mjs --context-id <preview ctx> --site <site> --route </path>, or pass --layout-file. It finds every ComponentRef rendering, picks the path the way the SDK does, fetches it, and judges the response against the beta parser.

SymptomCauseSignal
Nothing renders, <style> presentatomsConfig missing in Providers.tsxno log at all
Nothing rendersMMS non-200console.error … failed to fetch … HTTP 404
Nothing renders although MMS is 200body served as application/json: the fetcher pre-parses it and the beta JSON.parses the objectfailed to parse … "[object Object]" is not valid JSON
Nothing rendersbad JSON, or the stale nested Document shapefailed to parse / empty render
Wrong (default) variantSitecore sends FieldNames, the SDK reads lower-case fieldNames. Edge also rewrites an unknown variant to "Default"probe prints WARN params.FieldNames … ignored
A code component vanishedits params carry a ComponentRef param, so it is diverted before the map lookupfailed to extract path from ComponentRef
Renders unstyledno compiler registered, or Pages Router templateno log
MMS fetched from the wrong hostedgeUrl / NEXT_PUBLIC_* set, but SITECORE_EDGE_PLATFORM_HOSTNAME notURL in the error
Whole page HTTP 500, x.trim is not a functiona field OBJECT bound ($state "/fields/X") to a plain-string propbind "/fields/X/value", or use the field schemas
Lock green but No renderer for component type: Xtwo src/atoms/index.* files: the bundler loads .tsx, the CLI .tsserver log
Null render persists after MMS is fixedSSG cached the null render (s-maxage=31536000)x-nextjs-cache: HIT; revalidate or rebuild
Values authored into a Document's state.fields never showthe wrapper overwrites state.fields / state.params with the rendering's (#654)bind to datasource fields instead
Kit atoms import "/lib/atoms-utils" (absolute path)Content Kit installed without components.jsongrep -rn 'from "/' src; fix to @/lib/atoms-utils
Design Studio shows nothingcatalog missing → atoms:error {type:'atoms-missing'}see references/design-studio-bridge.md
  • To dump the raw layout params, use content-sdk-debug-layout-probe.
  • Prove a fix with next build && next start, never next dev.
  • Preview proves nothing about live.

9. Design Studio bridge

  • Mode. library-low-code sets isLowCode, and DesignLibraryApp routes it to DesignLibraryLowCodeComponent.
  • Message sequence (since #652 / #654):
    1. READY
    2. atoms:catalog (props as JSON Schema, plus legacy, version, stylingSolution), or atoms:error {type:'atoms-missing'}
    3. Design Studio sends component:atoms:preview {document}; fields and params travel inside document.state (the component:update leg is gone)
    4. The app runs validateAtomsDocument; on failure atoms:error {type:'validation', issues, formatted} (meant to be fed back to the AI generator), no render
    5. RENDERED, or atoms:error {type:'render'}
  • Any library session posts the catalog when one is configured.
  • Theme preview (#642): Design Studio or Pages posts theme-update {message:{css}}; in editing mode with theming.mode !== 'none' the app injects <style id="sitecore-theme-preview"> last in <head>. Needs the Providers theming prop.
  • Editing chromes: <code type="text/sitecore" chrometype="atom" class="scpm"> per atom, in edit mode only.
  • Where to find it. In Design Studio, Studio → Create component opens the builder with Layers, Selected Atom and an Atoms panel listing the catalog (seen 2026-11-05, stamp 20261021204512, custom atoms included). An existing code component opens without it, so do not judge availability from that.
  • The editing host log cannot confirm this. It records problems such as unknown components, not healthy sessions, so mode: library entries do not mean low-code is off.
  • Which tenants have the builder, and how it is switched on, is [UNVERIFIED].
  • Capabilities (from 20261104121033). The build writes capabilities.designLibrary.atoms.metadata.catalog into .sitecore/metadata.json, and /api/editing/config returns it (measured locally). Whether Design Studio reads it is [UNVERIFIED]: the panel listed the atoms on a stamp without it.

10. Backend surfaces and open items

  • No API that creates atoms, Documents or theme tokens is known. Who writes MMS is [UNVERIFIED] (references/design-studio-bridge.md).
    • The Components API (GA) has type: Hosted drafts with variant code (example <Button>Click</Button>) and model-suggestion {atoms: string}.
    • Activation is one-way, and the API needs an environment automation client (an org client gets 401).
    • theming.mode: 'site' adds a <link> to {edge}/authoring/api/v1/themes/delivery/{site}/web-css?contextID=… and the body class sc-ds-theme. That endpoint returned 404 for anonymous and bearer calls on the test tenant (2026-10-02). The SDK only delivers theme CSS; it does not author or store tokens.
    • See references/apis-and-theming.md. FEaaS "low code components" are a different system.
  • Open [UNVERIFIED] items:
    • which tenants have the low-code builder, and what switches it on
    • the real MMS content type and cache headers, and whether Document edits revalidate pages (the fetch carries no sc:* tag). A null render is cached for a year (§ 8)
    • Pages inline editing inside atoms
    • theme delivery
    • deploy-time CSS
    • the model-suggestion payload

Version history and the dated matrix: references/version-matrix.md. Content Kit inventory and install recipe: references/content-kit.md. Writing an atom: content-sdk-app-router-atom-create. Which existing components to move to atoms: content-sdk-atomic-design-assessment.

Content SDK OSR (App Router)

Cache Sitecore reads with Next.js Cache Components and invalidate them when Experience Edge reports a publish, instead of waiting for a TTL or redeploying. The mechanism is deterministic cache tags: the read path stamps a tag, the webhook route derives the same string from the publish payload, and revalidateTag connects them with no shared state.

The Edge side (credential, registering the webhook, lastRuns, auto-disable) lives in sitecoreai-edge-admin-webhooks. This skill owns the head app.

1. Decide first: which template

nextjs-app-router-cache-componentsnextjs-app-router (plain, the default)nextjs (Pages Router)
SDK OSRYes: src/app/api/revalidate/route.ts + tagged 'use cache' helpers in src/lib/cache/No route, no 'use cache'No: time-based revalidate only
Freshness without OSRTTL only (Next default profile: revalidate 900 s)Time window + a redeploy after publishrevalidate: 5 under SSG
TrapThe 2.4.0 tag defects (§ 2)Per-call fetch({ next: { tags } }) is dead: the SDK GraphQL client forwards only headers, so hand-wired fetch tags never reach the cacheNo SDK res.revalidate helper
  • If "fresh within seconds of publish" is a requirement, scaffold with --template nextjs-app-router-cache-components (still App Router: src/app/ exists, src/pages/ does not).
  • On the plain template the honest choices are: migrate (§ 8) or accept a time window plus a redeploy. Never hand-wire fetch tags.
  • The Angular template also wires an OSR route (createSitecoreRevalidateMiddleware). Out of scope here.

2. Version floor (hard rule) [probe-gated: P0]

VersionState
< 2.2.0No createSitecoreRevalidateRouteHandler, no cache-components template
2.2.0 – 2.4.xRoute exists. Item-level OSR cannot match a cached page, three upstream defects (below)
2.5.0-canary.20261001115411All three fixed. Same line removes tags[] from the request body
2.4.1 (2026-10-12)First stable floor. Release notes list all three fixes, and the shipped handler no longer reads tags from the body (code read 2026-10-13; not re-measured live)

The three 2.4.0 defects (fixed upstream in #619, #620, #623):

  1. GUID format. The webhook builds a dashless GUID, the read side tags a hyphenated one. Item tags never match.

  2. Version segment. The read side tags :v<N> when layout reports itemVersion, the webhook tags :latest. Never matches.

  3. Dictionary over-invalidation. With sites passed (the template default), every call appends sc:dict:<site>:<locale> for every site, and every page carries its site's sc:dict tag. So any authorised POST marks every page stale (default locale of each site only). This masks 1 and 2: it looks like OSR works. Without sites, item OSR is a silent no-op and pages refresh on the 900 s TTL.

    What 3 does depends on the runtime (live, 2026-10-02). On a local next start, the re-render after the first purge reused the cached layout data, so content stayed stale. On Vercel the re-render refetched layout, so 2.4.0 + sites delivered the new content on every publish (two of two, plus a direct POST): the cost is that every authorised POST re-renders every page of every site in sites.json (an unrelated page went STALE on an item-only POST; the canary left it HIT). A 2.4.0 app on Vercel therefore "works" and hides the defect behind a sitewide purge. Do not read a passing end-to-end test on 2.4.0 as item-level OSR.

Rules:

  • Floor = nextjs 2.4.1, the first stable release containing #619 + #620 + #623 (2026-10-12). Before a newer claim, run npm view @sitecore-content-sdk/nextjs dist-tags and check the release notes. Do not ship the 2.4.0 workaround (strip itemVersion, rewrite identifiers to hyphenated GUIDs) unless the floor is unreachable; it is unverified.
  • Pin the SDK exactly across the boundary. The fix changesets (2.4.1, and the 2.5.0 canary before it) are all patch and none flags the tags[] removal, so a ^2.4.0 lockfile refresh (which now pulls 2.4.1) silently breaks any caller that posts { "tags": [...] }. Grep for tags: callers before upgrading.
  • The upgrade also changes template files (route.ts, the template's agent docs): route it through content-sdk-upgrade-assistant.

3. The route contract

// src/app/api/revalidate/route.ts
import { createSitecoreRevalidateRouteHandler } from '@sitecore-content-sdk/nextjs/route-handler';
import type { SiteInfo } from '@sitecore-content-sdk/nextjs';
import scConfig from 'sitecore.config';
import sites from '.sitecore/sites.json';

export const { POST } = createSitecoreRevalidateRouteHandler({
  defaultLocale: scConfig.defaultLanguage,
  sites: sites as SiteInfo[],
  cacheProfile: { expire: 0 },   // § 5
});
OptionDefaultEffect
secretSITECORE_REVALIDATE_SECRETCompared to the x-revalidate-secret header with plain !==
cacheProfile'max'Passed to revalidateTag(tag, profile)
defaultLocale'en'Locale for rows without entity_culture
sitesnone2.4.0: appends every site's sc:dict on every call. 2.4.1+: maps DictionaryEntry rows to sc:dict:<site>:<locale> by longest site-name prefix; an unknown site is skipped with a debug log only (case-sensitive)

Responses: 200 { revalidated: true, tagsCount, invocation_id, continues } · 401 secret mismatch · 400 body not JSON, not an object, or zero resolved tags · 500 error.

Mapping: strip a -layout / -media suffix from updates[].identifier, lowercase, strip braces, build sc:item:…. entity_definition and operation are ignored, so a Delete row (live: no entity_definition key at all, operation: "Delete", sent on unpublish and on delete) resolves to the page's sc:item tag like an update, and the next read finds Edge's layout null, so the route renders not-found (the rows are live; the 404 render was not run end to end). Only the removed page's own rows arrive: pages linking to it are not refreshed (§ 7). 2.4.0 also accepts tags[] (an sc:-prefixed string verbatim, a bare value as an item id); 2.5.0 does not: a tags-only body gets 400 (live, canary), and tags[] next to updates is silently ignored.

An OnUpdate Edge webhook is the only caller that gives item precision. A CM webhook payload has no updates, and an OnEnd static body has no rows: on 2.5.0 both resolve zero tags and get 400. Edge retries a non-2xx without backoff until the 10-failure auto-disable, so one such publish disables the webhook (live, with a 401: 10 deliveries in 7 s; with a 400: 10 over 137 s). The same holds for a wrong secret. So the secret is verified before the webhook can deliver: run the controls (Verify 2) against the deployed route first, and only then register (or enable) the OnUpdate webhook (sitecoreai-edge-admin-webhooks § 5).

4. Tag vocabulary

Tag2.4.1+ shape2.4.0 (legacy)
Routesc:route:<site>:<locale>:<seg/seg | _>same
Itemsc:item:<hyphenated-lowercase-guid>:<locale>sc:item:<guid>:<locale>:<vN | latest>
Dictionarysc:dict:<site>:<locale>same
  • Sanitiser: trim, lowercase, collapse [/:\s]+ to _. Tags are case-sensitive in Next.
  • collectSitecorePageCacheTags({ site, locale, path, route }) returns route + item tag. Pass route, or the page is reachable by URL only.
  • The dictionary helper runs from src/i18n/request.ts, so every page carries sc:dict.
  • Next silently drops tags over 256 characters and keeps at most 128 tags per entry.
  • Public builders: collectSitecorePageCacheTags, buildSitecoreDictionaryCacheTag. The item / route / webhook builders are @internal: do not import them.

5. cacheProfile: 'max' vs { expire: 0 }

  • 'max' (SDK default) = stale-while-revalidate. The first visitor after a publish gets the old page and triggers the refresh. Fine for low-stakes content.
  • { expire: 0 } = blocking. The next request refetches from Edge. Recommended for delivery sites, and the shape Next documents for webhook route handlers.
  • Cost of { expire: 0 }: a broad purge turns traffic into uncached Edge calls. Edge allows about 80 uncached requests per second, then 429. Personalized pages multiply this: each variant has its own cache entry.

6. Personalization variants

The proxy rewrites variant requests to a _variantId_ path segment. The route tag strips it, so all variants of a page share route and item tags: one revalidation reaches every variant. Do not add per-variant tags. Variant mechanics: content-sdk-personalization.

7. Coverage gaps (what OSR never reaches)

ChangeWhy it is missedFallback
Shared datasource onlyThe page entry carries only the route-item tag. Snapshot publishing re-emits the page's Item + LayoutData rows (live: a datasource-only publish refreshed the page on the 2.5.0 canary); runtime publishing does not (doc, not probed)Snapshot publishing, or sitewide
Partial designDocs disagree on whether dependent pages are re-emittedSitewide
Template, standard values, language fallback, Multilist targets, integrated GraphQL resolved at publishDependents are not re-emitted as rowsSitewide or TTL
A URL cached as 404, then the page is publishedA null page carries only the route tag; the publish sends the new item idA short cacheLife on misses only ({ revalidate: 60, expire: 600 }, keep expire > 300), or a wrapper that also calls revalidatePath for new routes
SiteInfo row (site settings)Becomes a junk item tag (sc:item:<sitename>:all…)Sitewide
A page is unpublished or deletedEdge sends Delete rows for that page only (live); pages whose navigation or lists link to it get no rowSitewide after removals, or TTL
Sites added after buildNot in .sitecore/sites.json, so 2.4.1+ skips their dictionary rowsRebuild
A low-code (atoms) Document edited in MMSThe MMS fetch carries no sc:* tag [UNVERIFIED]TTL; and on beta.atoms the cache-components template returns 500 on every ComponentRef page (measured), its webhook module equals 2.4.0 (content-sdk-app-router-atoms)
A second localeA dictionary fetch nobody reads still tags every page sc:dict; per-locale OSR (sc:dict:<site>:<locale> for a non-default locale) is still unprobedVerify per locale (content-sdk-app-router-dictionary-and-i18n)
Multiple URLs / regionsLive: one revalidation reached both the production alias and the per-deployment URL; each URL is its own CDN entry, so under 'max' each serves one stale read before refreshing. Multiple regions not testedVerify live

Sitewide fallback: a separate route (its own secret check) that calls revalidatePath('/', 'layout'), called from the pipeline after a bulk publish is readable on Edge. Do not feed it from an OnEnd webhook: one publish produced three OnEnd deliveries, two before Edge had the content (live), so a purge on those re-caches the old content. The post-publish redeploy stays the last resort. Keep a TTL as a backstop either way: a receiver that is down past Edge's retries (seconds to about 2 minutes) loses the delivery.

8. Migrating a plain-template app

Treat it as a porting task, not a one-line change. Scaffold a reference app with --template nextjs-app-router-cache-components at the app's exact SDK version and diff against it.

  1. next.config.ts: cacheComponents: true.
  2. sitecore.config.ts: dictionary.caching.enabled = false (the in-process dictionary cache outlives the tags).
  3. Add src/lib/cache/get-sitecore-page.ts, get-sitecore-dictionary.ts, get-sitecore-error-page.ts from the reference (each: 'use cache' as the first statement, fetch through the single client, cacheTag every applicable tag).
  4. Page and src/i18n/request.ts read through the helpers; preview (draftMode()) reads stay direct.
  5. generateStaticParams returns the build-validation placeholder, never [] (the opposite of the plain template).
  6. Remove export const dynamic = 'force-dynamic' segments; wrap cookies() / headers() / draftMode() consumers in <Suspense>.
  7. Port app-specific components the template lacks (for example a partial-design dynamic placeholder).
  8. Add the route (§ 3) and SITECORE_REVALIDATE_SECRET; delete any hand-written revalidate route and any per-call fetch tags.
  9. Error pages: take the reference app's not-found.tsx, layout.tsx and the setCachedPageParams calls before every notFound() verbatim; keep the authored /404 a normal page with noindex (never notFound() for it, never a request API in not-found.tsx). Two measured upstream gaps: the error render sees empty getCachedPageParams() (a non-default-locale 404 shows the default language), and the template global-error.tsx pulls the server Layout into the client graph. Accept or work around them as references/migration-traps.md § 1, 2, 4 and 5 describe.
  10. Local e2e on Windows: experimental.isrFlushToDisk: false, or a case-variant request half-rewrites a prerendered page on disk (§ 3 there).
  11. Prove the migration on a Vercel Preview with scripts/check-served-html.mjs before anything reaches production (Verify step 0). Every trap in references/migration-traps.md passed build, next start and a full local e2e.

Hard rules

  • Unset secret = open endpoint (live on 2.4.0 and the 2.5.0 canary: no header, 200). When SITECORE_REVALIDATE_SECRET is unset or blank, the handler checks nothing and anyone can force invalidation. Set it on every deployment target (production, preview, development) and fail closed: if (!process.env.SITECORE_REVALIDATE_SECRET?.trim()) return new Response(null, { status: 503 }) before delegating to the SDK POST. Never weaken the check to "make the webhook work"; fix the caller's header.
  • 'use cache' is the first statement in the function body. A helper that fetches before it is not cached and fails silently.
  • Never cache the preview path. getPreview / getDesignLibraryData under draftMode() stay outside 'use cache'.
  • Never call revalidateTag from a component. Invalidation belongs to the route handler. A server-to-server webhook calling it from a Route Handler is correct (the exception to content-sdk-app-router-route-handler-vs-server-action).
  • Tag completeness is the correctness condition. A helper that caches but under-tags is unreachable by any publish.
  • Never cache personalized, visitor-specific or request-dependent responses under content tags.
  • Never turn an Edge error into notFound() (a try/catch around the page read in page.tsx or generateMetadata): the route cache stores a 404, or title-only metadata, for a real page. Let it throw: a 500 is not cached.
  • Never prerender a notFound() param, and never read a request API in not-found.tsx. Together they emptied every page's PPR resume on Vercel (live 2026-10-15: pages cut at ~21 KB, no </html>, nothing hydrated) while next start was clean; the request API alone makes every unknown path a 500 (DYNAMIC_SERVER_USAGE).
  • No Cache Components change reaches production without a served-HTML pass on a Vercel Preview (Verify step 0), and the same guard against the production deployment before it is promoted.

Verify against reality

A preview pass and a local next start prove nothing about the live cache (preview has no Edge webhook at all).

  1. Served HTML on the deployed origin (any Cache Components app, OSR or not). next start does not run Vercel's separate PPR resume invocation, so a resume that comes back empty is invisible locally. Run against the branch's Vercel Preview, then against the production deployment before it is promoted:
    MSYS_NO_PATHCONV=1 VERCEL_PROTECTION_BYPASS=… node scripts/check-served-html.mjs https://<deployment> \
      / /<locale> /<one-page-per-page-type> --expect-404=/zz-missing,/<locale>/zz-missing,/<page-type>/zz-missing
    
    Each path twice (cold resume, then cache HIT): status, </html>, flight chunks, size floor. When a known-broken deployment exists, run it there too: the guard must FAIL (negative control). An authored /404 page is a normal 200 page (noindex) in the template shape: list it with the content paths, not under --expect-404.
  2. Static: npm ls @sitecore-content-sdk/nextjs meets § 2; the route exists; the secret comes from env; cacheComponents: true; no per-call fetch tags (grep -rn "next: *{" src/).
  3. Controls against the deployed URL (never follows redirects, so an SSO 302 is not a false pass; a Vercel Deployment Protection 401 is reported as a FAIL, not as the route's 401; pass the bypass via VERCEL_AUTOMATION_BYPASS_SECRET):
    SITECORE_REVALIDATE_SECRET=… node scripts/revalidate-controls.mjs \
      --url https://<production-domain>/api/revalidate --item <page-item-guid> --site <site> --locale en
    
    Expected: no secret 401, wrong secret 401, OnUpdate rows 200 with tagsCount ≥ 1, DictionaryEntry row 200. A 200 proves tags were accepted, not that a page was purged. The script exits non-zero on any failure. The correct-secret controls really revalidate those tags.
  4. Tag equality (local): DEBUG=content-sdk:revalidate and compare the tag the read helper stamped with the tag the route derived. They must be byte-identical.
  5. End to end after a real publish (a live-tenant write: get the user's go-ahead first), asserting the content marker, never 200, tagsCount or cache headers:
    • Publish twice and judge the second: the first authorised POST after a deploy refreshes content even on a broken setup (P0 local; on Vercel 2.4.0 the first publish refreshed too).
    • Wait for the webhook, not for Edge: publish start → webhook took 86–175 s (live), 1–2.5 min after Edge already served the new value (23–60 s). Budget about 3 minutes before calling a publish missed. Poll the webhook's newest lastRuns entry (sitecoreai-edge-admin-webhooks).
    • Under 'max' the first read after the webhook is x-vercel-cache: STALE with the old marker; the next read (5 s later, live) has the new one. Under { expire: 0 } the first read should already be fresh.
    • Known-bad control: a page the publish did not touch must stay HIT on 2.5.x. If it goes STALE, you are on the 2.4.0 sitewide purge (§ 2).

References

  • scripts/revalidate-controls.mjs: the control set above (--help, --dry-run, --self-test). Live-tested 2026-10-02 against Vercel deployments of 2.4.0 and the 2.5.0 canary.
  • scripts/check-served-html.mjs: the served-HTML guard (Verify step 0; --help, --self-test). Live 2026-10-16: exit 1 on the broken production deployment, exit 0 on the fixed Preview, 404 paths included.
  • references/migration-traps.md: the measured traps of a plain-template migration, with the Next.js source behind each.
  • sitecoreai-edge-admin-webhooks: registering the OnUpdate webhook that calls this route.
  • content-sdk-personalization, content-sdk-upgrade-assistant, sitecoreai-publishing.
  • Next.js revalidateTag · Content SDK docs

Content SDK Component Data Strategy (App Router)

This app does not use getComponentData. Page and layout data come from getPage (or getPreview/getDesignLibraryData in editing). Component props are derived from the layout/placeholders; pass site and locale from route params.

When to use

  • User asks how to pass data to components, wire component props, or integrate custom/BYOC components.
  • Task involves component props, server vs client components, or BYOC.
  • User mentions "component data," "props," "BYOC," "server component," or "client component."

How to perform

  • Fetch at page/layout with getPage (or getPreview/getDesignLibraryData in draft). Pass site and locale from route params. Server Components use the client in server context; Client Components receive serializable props only. Register BYOC in the correct component map and pass props from layout.

Hard Rules

  • Data source: Page and layout from client.getPage(path ?? [], { site, locale }) in the catch-all page (or getPreview/getDesignLibraryData when draftMode() is enabled). All Sitecore-driven data flows from this single fetch at the route level.
  • Server Components: Use the same SitecoreClient in server context (e.g. in the page or layout). Pass data as props to children.
  • Client Components: Receive serializable props from parent (no functions or non-serializable values). Do not create a new client inside components. Pass data from page/layout level into components.
  • BYOC or custom components: Must be registered in the appropriate component map (.sitecore/component-map.ts or component-map.client.ts) and receive props in the shape the layout expects (e.g. fields, params).
  • Do not fetch layout or page data inside a child component (e.g. another getPage call); fetch at page/layout level and pass props.
  • Low-code components (beta.atoms) get fields / params seeded into json-render state ($state: /fields/<Field>). They are client-rendered after a server MMS fetch, with no ComponentQuery → content-sdk-app-router-atoms.

Stop Conditions

  • Stop if the user wants to fetch page/layout data inside a child component; recommend fetching at page/layout level and passing props.
  • Stop if server/client boundary is ambiguous and the change could cause "use client" or serialization issues; clarify and follow Next.js and app conventions.
  • Do not introduce getComponentData or duplicate getPage logic; this app uses getPage-only data flow.

References

Content SDK — Component-Level Navigation Pattern

A navigation that you actually control: queries you can read, types you can refactor, layout you can predict. Avoids the SXA Navigation Content Resolver (opaque, parameter-driven, fragile) and Integrated GraphQL on the rendering (query lives in Sitecore, hard to version). Instead the React component owns its data fetching via the SDK's GraphQL client.

When to use

  • Building navigation (main nav, footer nav, breadcrumb-adjacent, sidebar, sub-section nav) for a Sitecore head app.
  • Existing SXA Navigation Content Resolver is misbehaving, returning empty arrays, or its parameters (LevelFrom/LevelTo/Filter) are hard to reason about.
  • You want navigation that:
    • Stays in source control (queries + types + UI all in the React app)
    • Can be unit-tested without a tenant
    • Has type-safe responses
    • Scales to any depth without hitting Edge complexity limits
  • You're OK without inline-editing the nav (authors edit the underlying page items' NavigationTitle / NavigationFilter, not the nav rendering itself).

The pattern (one-page overview)

Server-side initial render:
  ┌─────────────────────────────────────────────┐
  │ NavigationCustom.tsx (Server Component)    │
  │   client.getData<NavLevel1Response>(        │
  │     NAV_LEVEL_1_QUERY, { root, language })  │
  │   ↓ returns root + L1 children +            │
  │     hasChildren flag per child              │
  └─────────────────────────────────────────────┘
                       ↓
  ┌─────────────────────────────────────────────┐
  │ NavBranch.tsx (Client Component) per item   │
  │   Renders link + chevron (if hasChildren)   │
  │   On hover/focus → ensureLoaded() →         │
  │     fetch('/api/nav-children?parent=...')   │
  │   Caches result in component state          │
  │   Renders dropdown with recursive NavBranch │
  └─────────────────────────────────────────────┘
                       ↓
  ┌─────────────────────────────────────────────┐
  │ /api/nav-children/route.ts (Route Handler)  │
  │   GET ?parent=...&language=...&maxItems=20  │
  │   client.getData<NavBranchResponse>(        │
  │     NAV_BRANCH_QUERY, { parent, language }) │
  │   Returns JSON array of child items         │
  │   NO router.refresh() side-effect           │
  └─────────────────────────────────────────────┘

Recursion: each NavBranch can itself render child NavBranch components inside its dropdown. Each child can lazy-load ITS children via the same route handler. The pattern scales to L3, L4, … without code changes — the only knob is the rendering parameter that caps depth.

Sitecore-side setup (per project)

  1. Rendering item at /sitecore/layout/Renderings/Project/<project>/NavigationCustom:

    • componentName = NavigationCustom
    • Datasource Location = query:$site|query:$sharedSites
    • Parameters Template = the new Parameters Template (next step)
    • OtherProperties = IsRenderingsWithDynamicPlaceholders=true
    • Datasource Template empty or pointing to a generic page template
  2. Parameters Template at /sitecore/templates/Project/<project>/Rendering Parameters/NavigationCustom Parameters with shared fields:

    FieldTypeNotes
    LevelDroplist 1|2Default 1. Do NOT name this Levels — that name collides with base-template inheritance on some Sitecore versions and the field becomes invisible in Pages. Level (singular) is safe.
    MaxItemsSingle-Line TextDefault 20 — per-level pagination cap; keeps Edge complexity bounded.
    ClassSingle-Line TextOptional CSS hook for layout variants.
  3. Add to Available Renderings under /sitecore/content/<tenant>/<site>/Presentation/Available Renderings/Navigation.

  4. Place on a page in Pages Editor:

    • Set Datasource = the item whose children should be the L1 nav (typically /Home).
    • Set Level = 2 for dropdowns; Level = 1 for flat clickable nav.
    • Publish + wait ~30s for Edge cache.
  5. (Optional) Headless Variants if you want author-selectable visual treatments — skip for v1.

Head-app file layout

Critical: only the Sitecore-registered .tsx lives under src/components/<Component>/. All support files (types, queries, sub-components, route handlers) live elsewhere or sitecore-tools generate-map will register them as separate Sitecore renderings or variants. See content-sdk-component-naming-traps.

src/
  components/
    NavigationCustom/
      NavigationCustom.tsx              # ONLY this file — Server Component, registered by gen-map
  lib/
    navigation/
      types.ts                           # NavItem, NavLevel1Response, NavBranchResponse, navLabel(), isNavVisible()
      queries.ts                         # NAV_LEVEL_1_QUERY, NAV_BRANCH_QUERY (string literals)
      nav-branch.tsx                     # 'use client' — recursive NavBranch with hover/focus/click + lazy fetch
  app/
    api/
      nav-children/
        route.ts                         # GET handler — uses SitecoreClient.getData, returns JSON

The L1 query (server-side)

query NavLevel1($root: String!, $language: String!, $maxItems: Int = 20) {
  item(path: $root, language: $language) {
    id
    path
    displayName
    navTitle: field(name: "NavigationTitle") { value }
    url { path }
    navFilter: field(name: "NavigationFilter") { value }
    children(first: $maxItems, hasLayout: true) {
      results {
        id
        path
        displayName
        navTitle: field(name: "NavigationTitle") { value }
        url { path }
        navFilter: field(name: "NavigationFilter") { value }
        hasChildren(hasLayout: true)
      }
    }
  }
}
  • hasLayout: true — excludes data items, datasources, settings nodes. Only pages.
  • hasChildren(hasLayout: true) — boolean flag per L1 item. Lets the client decide whether to render an expandable chevron WITHOUT a round-trip. Crucial for UX.
  • url { path } is the public-facing URL (the visitor href). NOT the Sitecore tree path (path) — that's for downstream fetches only.
  • Empirically safe at first: 20 with all these field-lookups against a real SitecoreAI tenant. See sitecoreai-edge-graphql-capture for limits.

The L2 route handler (NOT a server action)

// src/app/api/nav-children/route.ts
import { NextResponse } from 'next/server';
import client from 'src/lib/sitecore-client';
import { NAV_BRANCH_QUERY } from 'src/lib/navigation/queries';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const parent = searchParams.get('parent');
  const language = searchParams.get('language') ?? 'en';
  if (!parent) {
    return NextResponse.json({ error: 'parent required' }, { status: 400 });
  }
  const result = await client.getData(NAV_BRANCH_QUERY, { parent, language, maxItems: 20 });
  return NextResponse.json(result.item?.children.results ?? []);
}
query NavBranch($parent: String!, $language: String!, $maxItems: Int = 20) {
  item(path: $parent, language: $language) {
    children(first: $maxItems, hasLayout: true) {
      results {
        id
        path
        displayName
        navTitle: field(name: "NavigationTitle") { value }
        url { path }
        navFilter: field(name: "NavigationFilter") { value }
        hasChildren(hasLayout: true)
      }
    }
  }
}

WHY a route handler, not a Server Action:

  • Server Actions auto-trigger router.refresh() after completion (designed for mutations — re-fetch the RSC tree to reflect server state changes).
  • A nav fetch is a read. The refresh wipes all client state — dropdown closes, page re-renders to initial state, user sees an endless "loading then nothing" cycle.
  • Route handlers are pure JSON responses with zero React-tree side-effect.

This is a Next.js architectural rule, not a Sitecore quirk: reads → route handler, mutations → server action.

NavBranch (client component — hover + lazy load)

Key behavior, distilled:

'use client';
export function NavBranch({ item, language, maxItems, remainingLevels }) {
  const [children, setChildren] = useState<NavItem[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const fetchedRef = useRef(false);                            // de-dupe fetch
  const closeTimerRef = useRef(null);                          // hover intent-delay

  const expandable = item.hasChildren && remainingLevels > 0;

  const ensureLoaded = useCallback(async () => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    setLoading(true);
    try {
      const url = `/api/nav-children?parent=${encodeURIComponent(item.path)}&language=${language}&maxItems=${maxItems}`;
      const r = await fetch(url, { headers: { Accept: 'application/json' } });
      if (!r.ok) { fetchedRef.current = false; setChildren([]); return; }
      const data = await r.json();
      setChildren(data.filter(isNavVisible));
    } finally { setLoading(false); }
  }, [item.path, language, maxItems]);

  const handleOpen = useCallback(() => {
    if (closeTimerRef.current) { clearTimeout(closeTimerRef.current); closeTimerRef.current = null; }
    setOpen(true);
    void ensureLoaded();
  }, [ensureLoaded]);

  // 150ms intent-delay — don't close on brief mouseleave (user travelling toward dropdown)
  const handleClose = useCallback(() => {
    if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
    closeTimerRef.current = setTimeout(() => { setOpen(false); closeTimerRef.current = null; }, 150);
  }, []);

  return (
    <li
      className="relative"
      onMouseEnter={expandable ? handleOpen : undefined}
      onMouseLeave={expandable ? handleClose : undefined}
      onFocus={expandable ? handleOpen : undefined}
      onBlur={(e) => {
        if (expandable && !e.currentTarget.contains(e.relatedTarget as Node | null)) handleClose();
      }}
    >
      <div className="flex items-center">
        <Link href={item.url.path || '#'}>{navLabel(item)}</Link>
        {expandable && <button onClick={() => open ? handleClose() : handleOpen()} aria-expanded={open}>▼</button>}
      </div>
      {expandable && open && (
        <ul
          role="menu"
          // top-full FLUSH with parent's bottom — NO mt-*. Any visible gap here
          // causes mouseleave on <li> during cursor traversal, triggering flicker.
          className="absolute left-0 top-full z-50 min-w-48 ..."
        >
          {loading ? <li>Loading…</li> :
            children?.length ? children.map(c => <NavBranch key={c.id} item={c} language={language} maxItems={maxItems} remainingLevels={remainingLevels - 1} />)
            : <li>No items</li>}
        </ul>
      )}
    </li>
  );
}

Critical design choices (with rationale)

  1. hasChildren flag in L1 query: lets the client render the expandable chevron before any L2 fetch. Without it, you'd have to either fetch all L2 upfront (defeats lazy load) or render every L1 with a chevron (UI lies about expandability). Item.hasChildren(hasLayout: Boolean) is a cheap boolean.

  2. Route Handler for the L2 read (the bug we hit and fixed): Server Actions trigger router.refresh() → wipes client state → endless loading flicker. Route Handler returns JSON with zero React side-effect. Universal rule: client-triggered reads → route handler.

  3. Hover intent-delay (150ms): brief mouseleaves (e.g., crossing a tiny gap) don't immediately close. Re-entering within 150ms cancels the close. Standard popover pattern.

  4. No-gap dropdown positioning (top-full, no mt-*): the dropdown must be flush with the parent <li>'s bottom. Any visible CSS gap creates a zone where mouse is OUTSIDE <li>'s bbox AND outside the dropdown's DOM — triggers mouseleave on the <li> → close → flicker. Internal padding (p-1) provides visual breathing room.

  5. Recursive NavBranch (each branch fetches its own children): no flat tree code, no per-level branching. Same component works for L1, L2, L3, … The only stop condition is remainingLevels === 0.

  6. NavigationFilter respect (isNavVisible): items with a non-empty NavigationFilter field value are hidden. Matches SXA's "any filter set = hidden from default nav" convention. Conservative default; can be made configurable later.

  7. NavigationTitle override (navLabel): per-item author override of the link label. Falls back to displayName when not set. Standard Sitecore convention.

  8. Datasource = root, NOT a rendering parameter: one mechanism, no overlap. Author picks root via Pages' Content tab. Tested earlier with a Root rendering parameter — added confusion ("which wins?"), removed.

  9. Helper files live OUTSIDE src/components/: types, queries, route handler, NavBranch client component all under src/lib/navigation/ (or src/app/api/ for the route handler). Inside src/components/NavigationCustom/, only the Sitecore-registered .tsx. Otherwise gen-map registers helpers as Sitecore renderings or variants. See content-sdk-component-naming-traps.

Edge complexity

Empirically tested against SitecoreAI Edge on 2026-05-27:

  • L1 query (first: 20 + full field() lookups + hasChildren) → ✅ works
  • L2 nested in L1 (first: 5 + minimal fields, no field()) → ✅ works
  • L2 nested in L1 (first: 5 + any field() lookups) → ❌ "Query is too complex"

So a SINGLE L0+L1+L2 query is impractical with full fidelity. Per-branch lazy fetch sidesteps this entirely — each branch's children query has the same shape as the L1 query and stays within limits.

See sitecoreai-edge-graphql-capture for the full Edge limits catalogue.

Hard Rules

  • Reads use Route Handlers, not Server Actions. Server Actions auto-trigger router.refresh(); reads don't want that. Universal Next.js rule, especially load-bearing here.
  • hasChildren(hasLayout: true) on the L1 query so chevrons can render without a second fetch.
  • Dropdown <ul> flush with parent <li> — top-full, no mt-*. A visible gap causes endless mouseleave flicker. Internal padding for visual breathing room.
  • Hover intent-delay (≥120ms, usually 150ms) before closing — covers cursor traversal.
  • field(name:) only at root + L1. Don't try to nest field() lookups at L2 in a single query — Edge will reject as too complex.
  • hasLayout: true on every children call. Excludes data items, datasources, and structural nodes that shouldn't appear in a navigation.
  • Use url { path } for hrefs, NOT path. url.path is the public URL; path is the Sitecore tree path (for downstream queries only).
  • Datasource is the root. Don't add a Root rendering parameter — it duplicates the mechanism and creates "which wins?" ambiguity.
  • Helper files (types.ts, queries.ts, nav-branch.tsx, actions.ts-style fetchers) live OUTSIDE src/components/<Component>/. Put them in src/lib/<feature>/ or src/app/api/.
  • Parameter name Level (singular), not Levels. Plural collides with base-template inheritance on some Sitecore configurations and becomes invisible in Pages.
  • isNavVisible filter on every result set — both server-side (L1) and client-side (L2+ after fetch).
  • Server-rendered L1 is cacheable. The client.getData call runs server-side; Next.js can cache it via the standard fetch cache (with appropriate next: { revalidate } if needed).
  • Client-side L2 cache is per-NavBranch via useRef/useState. Re-hover doesn't re-fetch. No global cache needed for v1.

Stop Conditions

  • Don't try to recurse L2+ in a single server query. Edge complexity will reject it. Lazy-fetch per-branch is the only viable path at depth.
  • Don't use Server Actions for the L2 fetch. Even if your codebase has a "use server actions everywhere" preference, the router.refresh() side-effect breaks client state for reads.
  • Don't omit hasLayout: true — your nav will fill with datasources and settings items.
  • Don't bind nav behaviour to Pages Editor preview. Editor mode wraps renderings in chrome (<code type="text/sitecore">) which can interfere with mouse handlers. Test in the live published page, not the editor preview.
  • Don't co-locate helpers in src/components/<Component>/. Even though it feels right, gen-map will register them as Sitecore renderings or as variants of your main component, polluting the map.
  • Don't ship without publishing. Edge serves the cached layout; un-published rendering parameter changes (like Level=2) won't propagate until publish + ~30s.

Verification

  • L1 renders server-side on initial page load (visible in view-source HTML).
  • Each L1 item with children has a chevron; items without children don't.
  • Hover an L1 item with chevron → dropdown opens with "Loading…" briefly → resolves to children.
  • Re-hover → instant (no re-fetch, no loading flash).
  • Mouse leaves dropdown → 150ms grace → closes cleanly. No flicker.
  • Mouse moves from L1 into dropdown via the empty area between them → dropdown stays open (no-gap rule).
  • The Network tab shows ONE GET /api/nav-children?parent=... per branch on first hover. None on re-hover.
  • React DevTools shows no router.refresh() events on hover (proves you're using a route handler, not a server action).

Related

  • content-sdk-resolver-patterns — why this pattern beats Navigation Content Resolver and Integrated GraphQL for navigation.
  • content-sdk-component-naming-traps — the rule that forces helper files out of src/components/<Component>/.
  • sitecoreai-edge-graphql-capture — Edge complexity limits this pattern works around.
  • content-sdk-debug-layout-probe — for verifying layout response shape when integrating with Sitecore.
  • content-sdk-variants-vs-siblings — for adding visual variants (e.g., NavigationCustom.MegaMenu.tsx).
  • content-sdk-app-router-graphql-data-fetching — the SDK's client.getData API used here.

References

  • Reference implementation: the layout in § "Head-app file layout" is the complete surface — one registered component, src/lib/navigation/{types,queries,nav-branch}, one route handler — and the code blocks in this skill are its load-bearing parts verbatim. (The component was called Navigation_Custom when first built; it is NavigationCustom here because content-sdk-component-naming-traps trap 6 makes an underscored name version-sensitive.)
  • Edge complexity test: see sitecoreai-edge-graphql-capture for the empirical ceiling.
  • SDK API: SitecoreClient.getData<T>(query, variables, fetchOptions) — node_modules/@sitecore-content-sdk/content/types/client/sitecore-client.d.ts:122.
  • Next.js Server Actions vs Route Handlers: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations

Content SDK Component Registration (App Router)

Register components in the Sitecore component maps so the layout and editing pipeline can resolve and render them. This app has two maps: server and client.

When to use

  • After scaffolding or adding a new Sitecore component (must be registered).
  • User reports a component not rendering, "component not found," or layout/placeholder showing raw component name.
  • Task involves .sitecore/component-map.ts or .sitecore/component-map.client.ts.
  • User asks how to register a component or fix component resolution.

How to perform

  • Both maps are GENERATED, not hand-written. .sitecore/component-map.ts (Server) and .sitecore/component-map.client.ts (Client) are produced from src/components/ by sitecore-tools project component generate-map, which the scaffold wires into both npm run dev and npm run build (npm-run-all --serial sitecore-tools:generate-map …), plus a --watch variant during dev. So the normal way to register a component is to create the file in src/components/ and re-run dev/build.
  • Refresh manually with npm run sitecore-tools:generate-map. Edit a map by hand only when the generator genuinely cannot express your case — and expect the next dev/build to overwrite it.

Worked example

This is what the generator emits, shown so you can recognise a correct map and spot a broken one — not a template to type out. The map key is the layout componentName (case-sensitive). Each entry spreads the imported module ({ ...Promo }). A Server Component appears in component-map.ts only. A 'use client' component appears in both maps — the server entry tagged componentType: 'client', the client entry untagged.

// .sitecore/component-map.ts — Server map
import { NextjsContentSdkComponent } from '@sitecore-content-sdk/nextjs';
import * as Promo from 'src/components/Promo/Promo';
import * as StatsBand from 'src/components/StatsBand/StatsBand';

export const componentMap = new Map<string, NextjsContentSdkComponent>([
  // ...built-ins from the scaffold (BYOCWrapper, FEaaSWrapper, Form) stay as-is...
  ['Promo', { ...Promo }],                                    // server component
  ['StatsBand', { ...StatsBand, componentType: 'client' }],  // client comp placed in a server placeholder
]);

export default componentMap;
// .sitecore/component-map.client.ts — Client map ('use client' components only)
import { NextjsContentSdkComponent } from '@sitecore-content-sdk/nextjs';
import * as StatsBand from 'src/components/StatsBand/StatsBand';

export const componentMap = new Map<string, NextjsContentSdkComponent>([
  // ...built-ins (BYOCWrapper, FEaaSWrapper, Form)...
  ['StatsBand', { ...StatsBand }],
]);

export default componentMap;

A wrong/missing key renders <MissingComponent>. If a component is missing from a map, the fix is almost always re-run the generator, not add the line by hand — a component absent after regeneration usually means it is not where the generator looks (src/components/) or does not export what it expects.

Hard Rules

  • Every component rendered from Sitecore layout must be registered — but achieve that by running npm run sitecore-tools:generate-map (or just npm run dev / npm run build), not by editing the maps. Do not hand-edit generated entries unless the generator cannot handle the case.
  • Server components (no 'use client'): the generator emits them into .sitecore/component-map.ts only.
  • Client components ('use client'): the generator emits them into both maps — .sitecore/component-map.client.ts, and .sitecore/component-map.ts tagged componentType: 'client'. Editing API routes consume both (e.g. clientComponents from the client map). Verified against generated output: in a 32-component app all 9 client components appeared in both maps.
  • Component names come from the file/folder name, so renaming a component file renames its map key and breaks the layout binding. Rename deliberately and update the Sitecore rendering to match.
  • Do not remove or rename registrations without updating all references (layout, editing routes).
  • Atoms (beta.atoms only) are not in .sitecore/component-map*. A rendering whose params carry ComponentRef bypasses the map entirely (checked after FEaaS/BYOC, before the map lookup) → content-sdk-app-router-atoms.

Stop Conditions

  • Stop if it is unclear whether the new component is Server or Client; ask or follow app convention.
  • Stop if modifying the maps would break existing layout or editing; suggest a safe change or ask for confirmation.
  • Do not edit .sitecore/metadata.json or import-map unless the task explicitly requires it.

References

Content SDK Component Scaffold (App Router)

Scaffold new Sitecore components so they integrate with the layout and editing pipeline. This app uses App Router with separate server and client component maps.

When to use

  • User asks to add a new Sitecore component, create a component from scratch, or scaffold a component.
  • Task involves creating a new React component that will be rendered from Sitecore layout/placeholders.
  • User mentions "new component," "add component," or "component file structure."

How to perform

  • Create a new file under src/components/ (or existing feature folder). Define props (fields, params), export a single default component.
  • Decide Server vs Client: default Server; add 'use client' only if the component needs hooks or event handlers.
  • Do not register it by hand. The component maps regenerate from src/components/ during npm run dev and npm run build; run npm run sitecore-tools:generate-map to refresh them on demand (see the content-sdk-app-router-component-registration skill).
  • Run npm run build to verify, then confirm the component appears in the expected map.

Worked example

A Server Component is the default — value components (Text/Image/Link) and field types both import from @sitecore-content-sdk/nextjs. Convention is one folder per component: src/components/<Name>/<Name>.tsx.

// src/components/Promo/Promo.tsx — Server Component (the default)
import { JSX } from 'react';
import { Text, Image, Link } from '@sitecore-content-sdk/nextjs';
import type { TextField, ImageField, LinkField } from '@sitecore-content-sdk/nextjs';
import type { ComponentRendering, ComponentParams } from '@sitecore-content-sdk/nextjs';

export interface PromoFields {
  Title?: TextField;
  Image?: ImageField;
  Cta?: LinkField;
}

export interface PromoProps {
  rendering: ComponentRendering & { fields?: PromoFields };
  fields?: PromoFields;
  params?: ComponentParams;
}

const Promo = ({ fields }: PromoProps): JSX.Element => (
  <section>
    <h2>
      <Text field={fields?.Title} />
    </h2>
    <Image field={fields?.Image} />
    {/* guard field EXISTENCE, not value — empty fields stay authorable in Pages
        (see content-sdk-field-usage-image-link-text / -editing-safe-rendering) */}
    {fields?.Cta && <Link field={fields.Cta} />}
  </section>
);

export default Promo;

Needs hooks or event handlers (interactivity)? Make it a Client Component — add 'use client' as the first line. Everything else (props interface, field helpers, default export) is identical, and the generator takes care of placement: a 'use client' component lands in .sitecore/component-map.client.ts and in .sitecore/component-map.ts tagged componentType: 'client'.

Hard Rules

  • Place components under src/components/. Use existing folder conventions.
  • Define a props interface with the component's fields (e.g. fields: { title: Field; ... }) and any params. Use types from @sitecore-content-sdk/react or the app's types.
  • Export a single default component; one component per file unless the app pattern differs.
  • Server vs Client: Use Server Components by default. Add 'use client' only for interactivity (hooks, event handlers). The generator decides map placement from that directive — Server components into .sitecore/component-map.ts, Client components into .sitecore/component-map.client.ts and the server map tagged componentType: 'client'.
  • Prefer npm run sitecore-tools:generate-map over hand-editing the maps; register manually only when the generator cannot handle the change, and expect the next dev/build to overwrite it.
  • The component is not done until it appears in the expected map after regeneration (see the content-sdk-app-router-component-registration skill). Do not leave it unregistered.

Stop Conditions

  • Stop and ask if the component should be a Server or Client Component when the app does not have a clear convention.
  • Do not create components in .next/, node_modules/, or build output.

References

Content SDK Component Variants (App Router)

One component definition can have multiple presentations or data-driven variants. Keep registration and layout aligned. This app does not use getComponentData; layout/placeholder data comes from getPage.

When to use

  • User asks for different "variants," "versions," or "presentations" of a component.
  • Task involves rendering the same component type with different layouts or props based on data (e.g. variant field or style).
  • User mentions "component variants," "variations," or "multiple renderings."

How to perform

  • Prefer one component that accepts variant/style via props and branches internally; or multiple map entries if the app pattern uses one key per variant. Use layout/fields/params for variant; register in the correct component map (Server or Client). Align with existing app convention.

Worked example

The SDK resolves a variant from the rendering's params.FieldNames to a named export, case-sensitive. Same componentName, one folder, one file per variant (<Name>.<Variant>.tsx); generate-map merges every variant's exports into a single map entry.

// src/components/Promo/Promo.Card.tsx — a variant of Promo
import { JSX } from 'react';
import type { PromoProps } from './Promo';

export const Card = ({ fields }: PromoProps): JSX.Element => (
  <article className="promo-card">{/* card-specific layout, same fields */}</article>
);
export default Card;
// .sitecore/component-map.ts — `sitecore-tools project component generate-map` merges variants
import * as Promo from 'src/components/Promo/Promo';          // provides the default fallback
import * as PromoCard from 'src/components/Promo/Promo.Card'; // exports `Card`

export const componentMap = new Map<string, NextjsContentSdkComponent>([
  // main module spread LAST so its `default` wins as the fallback; `Card` stays a named export
  ['Promo', { ...PromoCard, ...Promo }],  // named export `Card` + default fallback under ONE componentName
]);

Resolution: FieldNames: "Card" → component.Card; empty / missing / "Default" → component.default fallback; any unmatched name → <MissingComponent> + console warning (case-sensitive: "card" ≠ "Card"). The variant also needs a CMS Headless Variant item to appear in the Pages dropdown. CM-side, a raw __Renderings write stores the variant item's GUID in FieldNames, not its name. Once any variant item exists, a missing FieldNames resolves to the alphabetically first variant, not Default. Full runtime contract + failure modes: content-sdk-variants-vs-siblings.

Hard Rules

  • Prefer a single component registration that accepts variant/style data (e.g. params or fields) and branches internally, over multiple map entries for the same logical component unless the app pattern uses separate registrations per variant.
  • Use props (fields, params) from layout to decide variant; do not rely on global state or URL for variant selection when data comes from Sitecore.
  • Register in .sitecore/component-map.ts (Server) or .sitecore/component-map.client.ts (Client) as appropriate. If the app uses one key per variant, register each; if one key with variant param, single registration. Follow existing app convention.
  • Keep the maps in sync via npm run sitecore-tools:generate-map (it also runs on npm run dev / npm run build) rather than editing them — the generator merges every <Name>.<Variant>.tsx export into the one map entry, which is easy to get wrong by hand.

Stop Conditions

  • Stop if the variant model (one registration vs many) is unclear; ask or follow the app's existing pattern.
  • Do not add new component map entries without ensuring layout and editing can provide the corresponding data.
  • Do not assume variant field names (e.g. "variant," "style") without checking the layout definition.

References

Content SDK language model (App Router)

The head app owns three things: which URL means which locale, how dictionary phrases reach components, and what the HTML says about its language. The CM side (environment languages, versions, fallback, translation, publishing per language) is sitecoreai-localization.

Tags: [measured 2026-10-02] = observed on a real tenant or a production build; [probe-gated: X] = not yet proven, X names the open check.

1. How a request becomes a locale

The scaffolded proxy chain is preview → botTracking → locale → multisite → redirects → personalize (proxy order: content-sdk-app-router-multisite-management).

  • LocaleProxy reads the PATH only. No cookie, no Accept-Language. Match: locales.find(l => path.includes('/'+l+'/') || path.endsWith('/'+l)). No match → x-sc-locale header → nextUrl.locale → default. It then rewrites to /<locale><path>; multisite prefixes /<site>, so the catch-all receives /[site]/[locale]/[[...path]].
  • locales comes from routing.locales in src/i18n/routing.ts, which the scaffold sets to the default language only.
  • Measured matrix [measured 2026-10-02], routing.locales=['en','de-DE']:
RequestResult
/de-DE/x[locale]=de-DE, 200 if a de-DE version exists
/de-de/x404: case-sensitive, rewritten under the default
/fr/about (unlisted)404: rewritten to /en/fr/about
/x/de-DE/y (locale mid-path)500: [locale] becomes x; the not-found page asks Edge errorHandling(language:"x"), gets null, and the SDK throws Cannot read properties of null (reading 'notFoundPage')
/en/x200, same page as /x (duplicate URL, no redirect)
any path with a .LocaleProxy skipped
  • One global default language. site.language in sites.json is read only by RedirectsProxy. A per-site default needs a custom proxy [probe-gated: G14 design decision].
  • A site name containing _ breaks ${site}_${locale} ("my_site_en".split('_') → site my, locale site). Rename the site.

Full matrix and source lines: references/locale-proxy-matching.md.

2. Adding a locale: four places must agree

  1. The CM: an environment language, versions of the site's pages and dictionary entries in it, published (runbook in sitecoreai-localization).
  2. routing.locales in src/i18n/routing.ts. Casing must equal the CM name exactly (de-DE, not de-de).
  3. LocaleProxy (reads routing.locales; nothing to edit unless you copied the list).
  4. SSG: getAppRouterStaticParams(sites, routing.locales) prerenders, per locale, exactly the routes that have a version in that language [measured: 12 en + 9 de-DE paths]. No 404 pages are prerendered.

Adding a locale only in the CM changes nothing in the app: the unlisted locale is rewritten under the default and 404s. Gate it:

node scripts/check-locale-drift.mjs --app <head-app> --site <SiteName> --context-id-env SITECORE_EDGE_CONTEXT_ID
node scripts/check-locale-drift.mjs --app <head-app> --languages en,de-DE      # offline
node scripts/check-locale-drift.mjs --self-test

It reads siteInfo.rootPath and item(<root>/Home).languages from Edge (public context id, query only) and FAILs on locale-not-in-cm, cm-not-in-routing, case-mismatch, a literal <html lang> with several locales, and flat useTranslations(); WARNs on a dictionary fetched but never read and on t(k) || ''. A live context id reports published languages; a preview id reports authored ones.

Waiving a finding is consumer-bound. A deliberate exception (e.g. a literal root <html lang> kept by decision, with a client component setting document.documentElement.lang) goes in <head-app>/.locale-drift-ignore.json:

{ "html-lang-hardcoded": { "reason": "<ADR / decision>",
  "consumer": { "file": "src/ui/html-lang.tsx", "pattern": "document\\.documentElement\\.lang\\s*=",
                "mountedIn": "src/Layout.tsx", "mountPattern": "<HtmlLang\\b" } } }

The finding is reported WAIVED (exit 0) only while file matches pattern AND mountedIn matches mountPattern, comments stripped first (a commented-out write or mount is not a consumer). Delete the consumer, its write or its mount and the FAIL returns plus waiver-unconsumed; a waiver with no reason, no complete consumer, an unknown rule id or an invalid regex is waiver-invalid (FAIL). A waiver never outlives the code that justifies it.

3. URL strategy

WantWhat actually controls it
Default unprefixed, others prefixed (as-needed)LocaleProxy's default behaviour
Redirect targets keep or drop the prefixredirects.appLocalePrefix in sitecore.config.ts (never / as-needed / always)
/en/ forced on the default (always)Not enforced on incoming requests; custom proxy code
Locale from browser or cookieNot supported; custom proxy code
No duplicate /en/xNot handled; redirect /<default>/… to /… yourself, or set the canonical (§ 7)

localePrefix in routing.ts is inert: the template uses neither next-intl createMiddleware nor createNavigation. It only mirrors appLocalePrefix.

4. Messages: one shape, site-namespaced

src/i18n/request.ts splits requestLocale (${site}_${locale}, set by setRequestLocale in the page) and stores the dictionary under messages[site].

  • Server component: const t = await getTranslations(site).
  • Client component: const t = useTranslations(site) under <NextIntlClientProvider>.
  • Porting trap (starter kits): useTranslations() + t('KEY') || '' assumes a flat shape. Against the template it renders the key (KEY), never '' [measured]. Either namespace every call or flatten in request.ts (messages = await client.getDictionary(...)) and change every call site at once.
  • Alternative for chrome labels: read client.getDictionary({site, locale}) once per request through React cache() into a typed label map with code defaults. One shipped multilingual app chose this after getMessages() inside renderings produced a host-only 500 on every 404 page (2026-09).
  • setRequestLocale must run before any next-intl API in the render. Do not fetch the dictionary twice (layout and page).

Shapes, migration diff and test mocks: references/message-shapes.md.

5. Key and phrase rules

[measured 2026-10-02, production build]

InputOutput
Missing key, t('X') and t('X') || ''site.X both: the || '' fallback is dead code
Key with a dot (A.B)treated as nesting → site.A.B (Edge itself serves dotted keys; next-intl's INVALID_KEY check runs only in development)
Phrase Hi {name}, no argumentHi {name} (no throw)
Phrase It's '{literal}'It's {literal}: ICU quoting eats apostrophes around braces
Phrase <b>x</b> via t() / t.raw()the literal string; use t.rich with handlers for markup
Untranslated / empty Sitecore phraseEdge returns the key as the value, so the UI shows the key

Rules: UPPER_SNAKE or PascalCase keys without dots; one constant map of keys in code; tests mock useTranslations: () => (k) => k. Detect untranslated phrases with "value === key" (the census in sitecoreai-localization does).

6. Missing language version = 404, and how to tell

  • getPage returns null when Edge has no route for that language → notFound() → the site's 404 for that locale [measured on a real page without a de-DE version]. The SDK never falls back to the default language. Fallback is a CM + Edge feature (sitecoreai-localization § fallback, gated by an environment patch).
  • A brand-new language version is empty (every versioned field blank, __Final Renderings empty): the route exists and renders a blank page, not a 404.
  • page.layout.sitecore.context.language and route.itemLanguage are the language actually served. If fallback is ever enabled they are the way to detect it [probe-gated: G3].

7. Links, <html lang>, SEO

Links. Edge url.path carries no language segment, on live as well as preview, and resolved rich-text internal links have none either [measured on live]. Prefix in code:

export function localizeHref(href: string, locale: string, defaultLocale: string): string {
  if (locale === defaultLocale || !href.startsWith('/') || href.startsWith('//')) return href;
  if (href === `/${locale}` || href.startsWith(`/${locale}/`)) return href;
  return href === '/' ? `/${locale}` : `/${locale}${href}`;
}

Apply it in the link component and wherever url.path is rendered. Rich-text bodies need a post-process or an authoring convention.

<html lang>. The template hard-codes <html lang="en"> in src/app/layout.tsx. Calling getLocale() there throws during static generation and makes every route dynamic [measured]. The pattern that keeps SSG [measured: ● kept]: delete src/app/layout.tsx and src/app/[site]/layout.tsx, add src/app/[site]/[locale]/layout.tsx that renders <html lang={locale}><body> plus Bootstrap, and give src/app/not-found.tsx its own <html>. A client HtmlLang effect is the fallback (crawlers and the first paint see the wrong value). Set dir from the locale (RTL list) in the same place. Code: references/seo-and-html-lang.md.

SEO. getPageMetadata emits no alternates; build alternates.canonical (with the locale prefix) and alternates.languages from the page's available languages (Edge item(path, language){ languages{ language{ name } } }, which lists only versions that exist on that surface). The sitemap route serves the CM sitemap, resolved by host only, with no locale in its cache key; single-language sitemaps carry no hreflang [measured]; multilingual output depends on the site's alternate-links setting [probe-gated: G9]. Sitemap/robots: content-sdk-app-router-sitemap-robots.

8. Editing language (Pages)

Defect [measured 2026-10-02]: the editing render handler fetches route (e.g. /) back through the proxy, so LocaleProxy assigns the default locale, while getPreview renders the body in sc_lang. In Pages with German selected, the body is German but dictionary phrases and <html lang> are English. With route=/de-DE everything is German.

Fix direction [probe-gated: P8-fix]: in draft mode, derive the locale from the preview payload before any next-intl call, and keep it inside routing.locales:

const effective = draft.isEnabled ? (page?.layout.sitecore.context.language ?? locale) : locale;
setRequestLocale(`${site}_${effective}`); // move below the getPreview/getPage call

9. Language switcher

The SDK ships none. Build it from useLocale() (the next-intl locale is the plain locale) and a prefix swap on the current path; offer only languages the page has (item.languages on the delivery surface, see § 7). Do not offer a locale that is not in routing.locales.

10. Cost: a dictionary nobody reads

request.ts fetches the dictionary on every uncached request (memory cache 60 s per process, dictionary.caching). If no component calls getTranslations/useTranslations, it is pure cost, and under OSR every page also carries an sc:dict tag (content-sdk-app-router-cache-components-and-osr). check-locale-drift.mjs WARNs dictionary-unused. Removing the fetch is a product decision; keep it if the app will translate.

Gotchas

TrapEffect
routing.locales left at the defaultother languages 404 (rewritten under the default)
Locale casing differs from the CM404 on the CM-cased URL
Locale segment mid-path500 from the not-found page, not 404
requestLocale undefinedmessages stored under the key "undefined", dictionary of defaultSite
A sites.json site Edge does not knownext build fails: [IV-007] Site "<name>" does not exist
Hand-written Edge preview query with literal first: ≥ 61"Query is too complex"; pass first as a variable (the SDK does)
Edge language argument is case-insensitivede-de returns de-DE content on Edge, while the app 404s /de-de/

Stop conditions

  • Stop before changing the ${site}_${locale} encoding: request.ts, every setRequestLocale and SSG params change together.
  • Stop before adding a locale that check-locale-drift.mjs reports as locale-not-in-cm; fix the CM first (sitecoreai-localization).
  • Stop before moving the root layout if the app has other top-level routes needing <html>; each root layout must render its own.

References

  • references/locale-proxy-matching.md: LocaleProxy algorithm, measured matrix, the 500 path.
  • references/message-shapes.md: nested vs flat, migration diff, mocks.
  • references/seo-and-html-lang.md: locale root layout, generateMetadata alternates, localizeHref.
  • CM side: sitecoreai-localization. Proxy order: content-sdk-app-router-multisite-management. Catch-all and not-found: content-sdk-app-router-route-configuration. defaultLanguage resolution: content-sdk-site-setup-and-env.

Content SDK Editing-Safe Rendering (App Router)

Ensure components behave correctly in SitecoreAI editing, preview, and design library. This app uses draftMode() and searchParams for editing data.

When to use

  • User asks about editing, preview, design library, or "component not working in editor."
  • Task involves draft mode, editing chromes, or design library integration.
  • Fixing issues where components render differently or break in editor vs published.
  • User mentions getPreview, getDesignLibraryData, or editing API routes.
  • Authors can't manage a field in Pages: empty fields are invisible in the editor, a submit button fires form validation instead of selecting its label, or a <label> jumps focus into its input instead of selecting the field. See "Authoring-safe components" below.

How to perform

  • In the page or layout: call draftMode(); when enabled, read editing params from searchParams, use isDesignLibraryPreviewData(editingParams) to choose getDesignLibraryData vs getPreview; otherwise use getPage. Editing routes: config route uses createEditingConfigRouteHandler, render route uses createEditingRenderRouteHandlers; set dynamic = 'force-dynamic' on both.

Hard Rules

  • Use draftMode() in Server Components (e.g. in the page or [site] layout). When draft.isEnabled, get editing params from searchParams and use isDesignLibraryPreviewData(editingParams) to distinguish: if true, use client.getDesignLibraryData(editingParams); otherwise use client.getPreview(editingParams). When not in draft mode, use getPage(path ?? [], { site, locale }).
  • Do not assume editing/preview context in components that might run in static or non-editing contexts; guard on draftMode().
  • Editing API routes: src/app/api/editing/config/route.ts uses createEditingConfigRouteHandler({ components, clientComponents, metadata }) (import from .sitecore/component-map, .sitecore/component-map.client, .sitecore/metadata.json). src/app/api/editing/render/route.ts uses createEditingRenderRouteHandlers({}). Set export const dynamic = 'force-dynamic' on both. Do not duplicate client creation; config and render routes use the same component maps as the app.
  • Never commit editing secrets; use environment variables and document in .env.example only.
  • Design Library modes include library-low-code on beta.atoms (low-code components, atoms:* bridge events) → content-sdk-app-router-atoms.
  • Editing language (measured 2026-10-02): with sc_lang=de-DE and route=/ the body renders German but the dictionary and <html lang> stay English, because [locale] comes from the route, not sc_lang. Fix and details: content-sdk-app-router-dictionary-and-i18n § 8.
  • Make field-driven components authorable in edit mode (see "Authoring-safe components"): gate field helpers on existence + edit mode (never on value alone), keep presentational forms inert while editing, and detach field-backed <label htmlFor> in edit. These break authoring in Pages but pass unit tests — verify in a real editor.

Authoring-safe components (component-level editing UX)

The plumbing above gets editing data into the page; this section keeps each component authorable once it's there. Symptom class: the page renders fine but an author can't select/manage a field in Pages. Applies to field-driven components (built with Text/RichText/Image/Link), especially anything interactive (forms, labelled inputs) or with optional fields.

Detect edit mode inside a component:

  • Client component: const { page } = useSitecore(); const isEditing = page.mode.isEditing; (useSitecore from @sitecore-content-sdk/nextjs; needs SitecoreProvider in the tree — the scaffold provides it). useSitecore() is the unified hook; there is no useSitecoreContext in Content SDK.
  • Server component (no hooks): derive from a Text/RichText field's metadata — const isEditing = !!fields?.SomeTextField?.metadata;. Sitecore emits field.metadata only in edit/preview. TextField/RichTextField extends FieldMetadata; ImageField/LinkField carry metadata only via & FieldMetadata, so read editing off a text field, not an image/link.

1. Empty fields must stay authorable — gate on existence + edit mode, never on value. {fields?.Cta?.value?.href && <Link .../>} hides the field in the editor too, so there's nothing to click. The SDK helpers already render the default empty-field editing placeholder when field.metadata is present + value empty + editable !== false, and render null when empty + published — they just have to be rendered:

{fields?.Cta && (isEditing || fields.Cta.value?.href) && (
  <Link field={fields.Cta} className="btn" />
)}

The existence check (fields?.Cta &&) stops an absent datasource field (e.g. a template you haven't finished building) from feeding undefined to the helper and crashing it. For repeated/flat fields (e.g. MetaValue1-3/MetaLabel1-3), render all rows in editing and .filter() to non-empty only when published.

2. Presentational forms must go inert in edit mode. A <form onSubmit={validate}> with a type="submit" button whose label is a field: clicking the button to author the label fires submit → validation errors + focus-stealing, so the field can't be managed.

function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
  e.preventDefault();
  if (isEditing) return;                       // no validation in the editor
  /* ...validate / set state... */
}
// submit button:
<button type={isEditing ? 'button' : 'submit'}>…</button>  // also neutralizes Enter-to-submit

3. Field-backed <label htmlFor> steals the click. A <label htmlFor="x"><Text field={NameLabel}/></label> focuses its associated input on click (native label behavior) instead of selecting the label field. When the label is a sibling of its input (associated only via htmlFor), drop the association in edit:

<label htmlFor={isEditing ? undefined : 'x'} className="field-label">
  <Text field={fields?.NameLabel} />
</label>

Published keeps the proper label → input a11y association (isEditing is false in normal mode).

4. Custom / transformed field presentation must stay editing-safe. If a component renders a field's raw field.value with its own markup — splitting a headline into animated spans, formatting a number, concatenating a string — instead of passing the field to <Text>/<RichText>, it never emits the editing chrome (field.metadata is dropped), so the field is not inline-editable in Pages (only the right-hand Content panel can change it), while sibling fields rendered through the SDK helpers stay inline-editable. This is the "some fields inline-edit, some don't" tell. Branch on edit mode — SDK field component when editing, the custom presentation when published:

export function KineticHeadline({ field }: { field: TextField }) {
  const isEditing = !!field?.metadata;                     // server-safe edit signal
  if (isEditing) return <Text field={field} tag="h1" />;   // ONE editable node, un-split
  return <h1 aria-label={String(field?.value ?? '')}>{/* split .kin-line spans */}</h1>;
}

Keep it one editable node in edit mode — never split one field across multiple <Text> (each would try to save the whole value → corruption). Preserve a11y in both branches (accessible name via aria-label; decorative pieces aria-hidden).

5. Integrated GraphQL (ComponentQuery) text fields must be fetched as { value jsonValue } — check the DATA path FIRST, not just the render. For a Shape-B / ComponentQuery component (fields.data.datasource…), a text field fetched as field(name:"X") { value } returns the raw string with no editing metadata, so it is not inline-editable no matter how you render it — <Text>, ed(), everything is downstream of a field that has no .metadata. This is the deeper cause behind "I already render through <Text> and it still won't edit": the render was never the blocker; the query was. Fix on the rendering item's ComponentQuery: request { value jsonValue } (the universal safe shape — .value keeps rendering working, .jsonValue carries { value, editable, metadata }), then render the metadata-bearing jsonValue:

type Cq<F> = F & { jsonValue?: F };
const ed = <F,>(f?: Cq<F>): F | undefined => f?.jsonValue ?? f;   // defensive: falls back to value-only
// ComponentQuery:  Title: field(name:"Title") { value jsonValue }
<Text field={ed(item.Title)} />   // reads the editable jsonValue; still renders if jsonValue absent

Image/Link fields already use { jsonValue } (already editable). When a Shape-B field won't edit, read the LIVE ComponentQuery first — a { value } text selection is the smoking gun; don't just inspect the component. (See content-sdk-app-router-graphql-data-fetching for the query; the value-vs-jsonValue asymmetry also affects rendering.)

Verify in a real editor, not jest. All five only surface in Pages (they are metadata-driven). A structural unit test that reads props directly passes regardless — Playwright/manual editor smoke is the gate.

Stop Conditions

  • Stop and clarify if the issue is preview vs design library vs published; behavior differs.
  • Do not change proxy or middleware order to "fix" editing; editing is driven by API routes and draft/preview data.
  • Do not recommend disabling secret validation without explicit user request and warning.

References

Content SDK GraphQL Data Fetching (App Router)

All Sitecore data fetching goes through the single client in src/lib/sitecore-client.ts. Use getPage, getDictionary, and related methods correctly. This app does not use getComponentData; layout data comes from getPage.

When to use

  • User asks how to fetch page data, layout, or dictionary phrases.
  • Task involves getPage, getDictionary, getErrorPage, getPreview, getDesignLibraryData, or getAppRouterStaticParams.
  • User mentions "sitecore client," "Layout Service," "page data," or "dictionary."

How to perform

  • Use the client from src/lib/sitecore-client.ts only. In the catch-all page: await params, then client.getPage(path ?? [], { site, locale }). For SSG use generateStaticParams and client.getAppRouterStaticParams(siteNames, locales). For preview use draftMode() and getPreview/getDesignLibraryData from searchParams.

Hard Rules

  • Use the single SitecoreClient instance in src/lib/sitecore-client.ts. Do not create a second client or instantiate SitecoreClient elsewhere.
  • Pass site and locale from route params (e.g. await params in the page). Do not rely on global state for site/locale in server code.
  • Catch-all page: client.getPage(path ?? [], { site, locale }). Params are a Promise (Next.js 15+); use await params to get { site, locale, path? }.
  • Preview: Use draftMode(); if draft.isEnabled, use client.getPreview(editingParams) or client.getDesignLibraryData(editingParams) from searchParams. Otherwise use getPage with site and locale.
  • SSG: generateStaticParams — use client.getAppRouterStaticParams(siteNames, locales) where site names come from .sitecore/sites.json (e.g. sites.map((s) => s.name)), locales from src/i18n/routing.ts (e.g. routing.locales.slice()). Return at least one default param when not generating full paths (e.g. { site, locale, path: [] }).
  • Config for the client comes from sitecore.config.ts; use environment variables, never hardcode secrets.

Stop Conditions

  • Stop if the task requires moving the client to another folder without clear requirement; suggest keeping a single instance in lib.
  • Do not add direct GraphQL or fetch to Layout Service bypassing the client unless the task explicitly requires it.

References

Content SDK Multisite Management (App Router)

Site resolution from the request (hostname or cookie); AppRouterMultisiteProxy rewrites to /[site]/[locale]/...path. LocaleProxy runs before multisite so next-intl and the site resolver see the correct locale.

When to use

  • User asks about multiple sites, hostnames, or site resolution.
  • Task involves .sitecore/sites.json, multisite config, or the proxy (src/proxy.ts).
  • User mentions "multisite," "site resolution," "hostname," "sites.json," or "proxy chain."

The proxy chain (template 2.4.0)

Source of truth: create-content-sdk-app@2.4.0 → dist/templates/nextjs-app-router/src/proxy.ts (lines 16-28, 105; the cache-components template's file is byte-identical).

export default function proxy(req: NextRequest, event: NextFetchEvent) {
  const preview = new PreviewProxy({ client, ...scConfig.api.edge });
  const botTracking = new BotTrackingProxy({ ...scConfig.api.edge, sites, fetchEvent: event });
  const locale = new LocaleProxy({ sites, locales: routing.locales.slice(), defaultLanguage: scConfig.defaultLanguage, skip: () => false });
  const multisite = new AppRouterMultisiteProxy({ sites, ...scConfig.multisite, skip: () => false });
  const redirects = new RedirectsProxy({ sites, ...scConfig.api.edge, ...scConfig.api.local, ...scConfig.redirects, skip: () => false });
  const personalize = new PersonalizeProxy({ sites, ...scConfig.api.edge, ...scConfig.personalize, skip: () => false });
  return defineProxy(preview, botTracking, locale, multisite, redirects, personalize).exec(req);
}
#ProxyWhy it sits here
1PreviewProxyAuthorizes preview / editing requests on the editing host; no-op elsewhere
2BotTrackingProxyDetects bots (isbot), sets the sc_bot cookie and sends a botPageView via fetchEvent.waitUntil. Must precede PersonalizeProxy: skipForBot (default true) reads sc_bot to skip the personalize lookup for bots ("Lightweight Tracking")
3LocaleProxySets the locale before anything resolves a site
4AppRouterMultisiteProxyResolves the site, rewrites to /[site]/[locale]/[...path]
5RedirectsProxyApplies authored redirects for the resolved site
6PersonalizeProxyLast: rewrites to the _variantId_ path; owned by content-sdk-personalization
  • Proxies are instantiated per request, inside the exported function, because BotTrackingProxy needs that request's NextFetchEvent. Do not hoist them to module scope.
  • Doc disagreement: Sitecore's Lightweight Tracking page says BotTrackingProxy "must be the first proxy", but the scaffold puts PreviewProxy first. Follow the scaffold: preview requests must be authorized before anything else, and the invariant that matters is bot tracking before personalize.
  • xmcloud-starter-js main lags the template: 5 proxies, no BotTrackingProxy, module-scope instances, although its package.json is on 2.4.0. Do not copy its proxy.ts as the reference; the create-content-sdk-app template is.
  • src/proxy.ts alone is enough on Next 16. next build lists Proxy (Middleware) with no middleware.ts. The template's own .agents/docs/AGENTS-router-specifics.md still says to add a src/middleware.ts re-export; that line is stale. Do not add one.

Hard Rules

  • Site list is in .sitecore/sites.json (generated by the Sitecore CLI or deployment). Avoid hand-editing unless the format is known.
  • Keep the template order: preview → botTracking → locale → multisite → redirects → personalize. Insert custom proxies relative to it; never move locale after multisite or botTracking after personalize.
  • Languages across sites (measured 2026-10-02): LocaleProxy ignores site.language (one global default). A site name containing _ breaks the ${site}_${locale} request key. A sites.json entry Edge does not know fails next build ([IV-007]). See content-sdk-app-router-dictionary-and-i18n.
  • Matcher: exclude API routes, _next/, sitemap, robots, healthz, sitecore/api/, -/ (media) and static assets so the proxy stays lightweight.
  • Config: sitecore.config.ts → multisite, redirects, personalize. Single SitecoreClient; pass the resolved site and locale from route params into getPage, getDictionary, etc.
  • Personalize options (skip, scope, timeouts, enabled): content-sdk-personalization and content-sdk-site-setup-and-env. Consent gating (PersonalizeProxy.skip on a consent cookie): content-sdk-tracking-consent.

Stop Conditions

  • Stop if the user wants to move locale after multisite or bot tracking after personalize; explain the dependency.
  • Stop if sites.json format is unknown and the change could break resolution; suggest checking SDK docs or CLI output.
  • Do not add a second site resolution mechanism; use the existing proxy and config.

References

Content SDK Route Configuration (App Router)

Single catch-all route and layout hierarchy. Site and locale are in the path; proxy rewrites incoming requests to /[site]/[locale]/...path.

When to use

  • User asks to change routing, add a route, or fix 404/not-found behavior.
  • Task involves catch-all route, placeholders, root layout, or Layout.tsx.
  • User mentions "[site]," "[locale]," "[[...path]]," "placeholder," or "layout hierarchy."

How to perform

  • Single Sitecore page: src/app/[site]/[locale]/[[...path]]/page.tsx. Use await params for { site, locale, path? }; pass to getPage and call setRequestLocale(\${site}_${locale}`)` at the top. Layout: app/layout.tsx → app/[site]/layout.tsx (Bootstrap, draftMode) → page. Not-found: use getCachedPageParams and getErrorPage in the route's not-found.tsx.

Hard Rules

  • Single Sitecore page: src/app/[site]/[locale]/[[...path]]/page.tsx. This is the only page that renders Sitecore content. Do not add another page or catch-all for Sitecore content.
  • Params: Next.js 15+ — params is a Promise. Use await params to get { site, locale, path? }. Pass site and locale to client.getPage(path ?? [], { site, locale }).
  • Locale for next-intl: Call setRequestLocale(\${site}_${locale}`)at the **top** of the page so next-intl andsrc/i18n/request.ts` see the correct locale. Do not omit when adding new page branches.
  • Layout hierarchy: app/layout.tsx → app/[site]/layout.tsx (Bootstrap with siteName={site} and draftMode()) → page. Do not put site/locale-specific data fetching in the root layout.
  • Placeholders are rendered by the layout (e.g. Placeholder component); do not change placeholder names or structure without aligning with Sitecore layout definition.
  • Missing language version = 404, per site and locale (measured 2026-10-02): getPage returns null, there is no default-language fallback. A locale segment mid-path (/Coverage/de-DE/x) makes Coverage the [locale], the not-found page asks Edge for errorHandling(language:"Coverage"), gets null and throws a 500. Language model: content-sdk-app-router-dictionary-and-i18n.
  • Not-found: src/app/[site]/[locale]/[[...path]]/not-found.tsx. For Sitecore-driven 404 use getCachedPageParams() from @sitecore-content-sdk/nextjs for site/locale, then client.getErrorPage(ErrorPage.NotFound, { site, locale }).

Stop Conditions

  • Stop if the user wants to add a second catch-all or a different URL shape for Sitecore pages; explain single-entry-point constraint.
  • Stop if changing the proxy order. The 2.4.0 template chain in src/proxy.ts is preview → botTracking → locale → multisite → redirects → personalize, instantiated per request with the NextFetchEvent (source: create-content-sdk-app@2.4.0 dist/templates/nextjs-app-router/src/proxy.ts:16-28,105). BotTrackingProxy must precede PersonalizeProxy, which reads its sc_bot cookie to skip bots (Sitecore's doc says bot tracking must be first; the scaffold puts preview first, follow the scaffold). xmcloud-starter-js main lags (5 proxies, no bot tracking): not a reference. Full rationale: content-sdk-app-router-multisite-management; personalize proxy: content-sdk-personalization; consent skip: content-sdk-tracking-consent.
  • On Next 16, src/proxy.ts alone runs as the proxy; do not add a src/middleware.ts re-export (the template's AGENTS doc saying so is stale).
  • Do not move or rename the catch-all file without updating all references.

References

Next.js — Route Handler vs Server Action

Server Actions and Route Handlers both run on the server and can be invoked from client components. They look interchangeable — but they're not. Picking the wrong one for the wrong job produces a class of "page mysteriously refreshes after every interaction" bugs that take hours to diagnose.

When to use

  • Adding any server-side endpoint that a client component will call.
  • Debugging a Next.js app where the page seems to reload / re-render unexpectedly after user interactions.
  • Scaffolding a new API surface and unsure which primitive to reach for.
  • Reviewing PRs that introduce 'use server' files or src/app/api/... routes.

The one-line decision rule

  • Server Action = the server is going to change state (DB write, file write, external API mutation, cache invalidation, redirect after action). The auto-refresh of the RSC tree is a FEATURE — your client UI should re-render with the new server state.
  • Route Handler = the server is going to return data (read from DB / API / GraphQL, compute a value, look something up). The lack of auto-refresh is a FEATURE — your client state survives the call.

In other words: mutations → Server Action. Reads → Route Handler.

How the auto-refresh side-effect works

Every Server Action invocation, after returning, triggers Next.js to:

  1. Refetch the React Server Component tree for the current route
  2. Update any RSC state with the new data
  3. Re-render the entire route

This is correct for mutations: after you write data, you want the UI to reflect the new server state without manual cache busting.

This is catastrophic for reads from client components that hold local state:

User hovers nav item
  → client state: open=true, loading=true
  → fetch via Server Action
  ← Server Action returns data
  → Next.js auto-refreshes RSC tree
  → entire route re-renders
  → CLIENT STATE IS LOST (NavBranch unmounts/remounts)
  → fresh render: open=false, loading=false, dropdown gone
  → user re-hovers, repeat

This produces the classic "endless loading flicker" symptom. Indistinguishable from a hover-state bug until you realize the page itself is re-rendering.

Quick comparison

ConcernServer ActionRoute Handler
FileAny .ts/.tsx with 'use server' directive, or inline async function in a Server Componentsrc/app/api/<path>/route.ts with export function GET/POST/...
Invocation from clientDirect function call (await myAction(args))await fetch('/api/path?...')
Type safetyYes — full TS contract through the function signatureManual — must parse JSON, validate at boundary
Auto-refreshes RSC treeYES — every callNO — pure response
Cacheable via HTTPLimited (action-specific)Yes — standard Cache-Control, Next.js fetch cache, CDN
Testable in isolationHard (needs RSC runtime context)Easy — curl, Postman, Vitest with fetch mock
StreamingLimitedYes via ReadableStream / NextResponse
Best forMutations (write/delete/update), form submissions, redirectsReads (GET data, compute, lookup), webhooks, public APIs, BFF endpoints for client components

Canonical examples

✅ Server Action — form submission that writes

// app/posts/[id]/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';

export async function updatePostTitle(postId: string, title: string) {
  await db.posts.update({ where: { id: postId }, data: { title } });
  revalidatePath(`/posts/${postId}`);   // explicit cache invalidation
}
// app/posts/[id]/EditTitle.tsx
'use client';
export function EditTitle({ id }: { id: string }) {
  return (
    <form action={(formData) => updatePostTitle(id, formData.get('title') as string)}>
      <input name="title" />
      <button>Save</button>
    </form>
  );
}

Why this is right: writing to the DB is a mutation; the auto-refresh ensures the form's surrounding UI (which reads the post title from a Server Component) reflects the new title.

✅ Route Handler — read called from a client hover

// src/app/api/nav-children/route.ts
import { NextResponse } from 'next/server';
import client from 'src/lib/sitecore-client';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const parent = searchParams.get('parent');
  if (!parent) return NextResponse.json({ error: 'parent required' }, { status: 400 });
  const result = await client.getData(NAV_BRANCH_QUERY, { parent });
  return NextResponse.json(result.item?.children ?? []);
}
// src/lib/navigation/nav-branch.tsx
'use client';
export function NavBranch({ item }) {
  const [children, setChildren] = useState(null);
  const onHover = async () => {
    const r = await fetch(`/api/nav-children?parent=${item.path}`);
    setChildren(await r.json());
  };
  return <li onMouseEnter={onHover}>...</li>;
}

Why this is right: it's a read; no server state is changing. The hover handler updates LOCAL state. A Server Action would auto-refresh the route and wipe children (and any other client state in the tree).

❌ Anti-pattern — Server Action for a read

'use server';
export async function fetchNavChildren(parent: string) {
  return client.getData(NAV_BRANCH_QUERY, { parent });    // a READ
}
'use client';
const onHover = async () => {
  const children = await fetchNavChildren(item.path);     // ← triggers router.refresh()
  setChildren(children);                                   // ← state set, then immediately wiped by the refresh
};

Symptom: dropdown opens → data loads → page "reloads" → dropdown closes → user re-hovers → repeat. The page isn't actually doing a hard browser reload; it's an RSC refresh that resets your component tree.

Hard Rules

  • Server Actions auto-trigger router.refresh() after returning. This is documented but easy to miss. Plan around it.
  • Reads from client components use Route Handlers. If you find yourself reaching for a 'use server' function to fetch data on hover/click/scroll/visibility, stop and write a route handler instead.
  • Mutations should use Server Actions (or accept the manual router.refresh() boilerplate if you really want a route handler — usually not worth it).
  • Pure data lookups from a Server Component are NEITHER — they're just async function calls in the Server Component body. Server Actions and Route Handlers are both for cross-runtime invocation (client → server).
  • revalidatePath / revalidateTag belong inside Server Actions — except for server-to-server webhooks. A Route Handler called by an external system (an Experience Edge publish webhook → /api/revalidate, see content-sdk-app-router-cache-components-and-osr) is the correct home: there is no client to refresh. Any other route handler calling them is a mutation and probably should be a Server Action.
  • If a route handler is called frequently (e.g., on every hover), add an HTTP cache header (Cache-Control: public, max-age=60) or use Next.js's fetch cache to dedupe upstream calls.
  • Server Actions can return data, but the returned value is consumed BY THE CLIENT after the auto-refresh fires. So if the client's state depends on the returned value, the state will be set AFTER the refresh wipe — sometimes that's fine (component remounts and uses fresh data), sometimes it produces the flicker. Route handlers are the cleaner contract for "client decides what to do with the data."
  • Form actions (<form action={...}>) inherently mutate from the user's perspective (POST + redirect/refetch). Server Actions are correct there even when the "action" technically reads.

Stop Conditions

  • Don't add 'use server' to a file you just want to "make server-side." Server-side execution and the Server Action runtime are different things. Pure server-side computation in a Server Component is just an async function call, no directive needed.
  • Don't put route-handler-like logic in a Server Action and call it from many client components. Each call refreshes the RSC tree — N parallel calls = N refreshes. Use a route handler.
  • Don't fight the auto-refresh with experimental_useOptimistic or manual state-restore. That's papering over the wrong architectural choice. Switch to a route handler.
  • Don't use route handlers for true mutations expecting cache invalidation. Without revalidatePath/revalidateTag (which only exist server-side and are awkward to call from a route handler), your other server-rendered UI won't reflect the write.

Verification

  • Open Network tab. Server Action invocations show up as POST requests to the current route URL with a special next-action header. Route Handler invocations show up as your declared HTTP method to the route URL.
  • Open React DevTools. After invocation, look for "Update Server Components Tree" events (Server Action) vs nothing (Route Handler).
  • Stamp window.__probe = Date.now() before the call and check after. Both should preserve the window object (no full browser navigation), but the RSC refresh from a Server Action will re-render client components from scratch (their state resets), while a Route Handler leaves them alone.

Migration sketch — converting a misused Server Action to a Route Handler

- // src/lib/foo/actions.ts
- 'use server';
- import { fetchSomething } from '@/lib/source';
- export async function getSomething(id: string) {
-   return fetchSomething(id);
- }
+ // src/app/api/foo/route.ts
+ import { NextResponse } from 'next/server';
+ import { fetchSomething } from '@/lib/source';
+ export async function GET(request: Request) {
+   const id = new URL(request.url).searchParams.get('id');
+   if (!id) return NextResponse.json({ error: 'id required' }, { status: 400 });
+   return NextResponse.json(await fetchSomething(id));
+ }
  // some-client-component.tsx
  'use client';
- import { getSomething } from '@/lib/foo/actions';
  const onSomething = async () => {
-   const data = await getSomething(id);
+   const r = await fetch(`/api/foo?id=${encodeURIComponent(id)}`);
+   const data = await r.json();
    setData(data);
  };

That's the entire migration. The function signature semantics are identical from the client's perspective (both are (id) => Promise<Something>); only the side-effect on the RSC tree differs.

Related

  • content-sdk-app-router-component-level-navigation — the worked Sitecore example where this skill's rule was learned the hard way (Server Action for a nav lazy-read caused the endless flicker).
  • content-sdk-debug-layout-probe — uses a Route Handler (correctly) for the layout-debug endpoint; another example of "read → handler."

References

Content SDK Sitemap and Robots (App Router)

Sitemap and robots.txt are served via route handlers and rewrites. Use the SDK route handler helpers and sites from .sitecore/sites.json.

When to use

  • User asks to add or change sitemap or robots.txt.
  • Task involves SEO, sitemap.xml, or robots route.
  • User mentions "sitemap," "robots," "SEO," or "rewrites."

How to perform

  • Sitemap: src/app/api/sitemap/route.ts with createSitemapRouteHandler({ client, sites }); robots: src/app/api/robots/route.ts with createRobotsRouteHandler({ client, sites }). Use sites from .sitecore/sites.json. Add rewrites in next.config.ts for /sitemap*.xml and /robots.txt with locale: false. Set dynamic = 'force-dynamic' if needed.

Where robots.txt content actually comes from

The route handler serves nothing of its own — the body is CMS content. createRobotsRouteHandler resolves the site from the request host, then calls client.getRobots(siteName), which issues one Edge query:

query RobotsQuery($siteName: String!) {
  site { siteInfo(site: $siteName) { robots } }
}

siteInfo.robots is the RobotsContent shared field on the site's Settings item — /sitecore/content/<Collection>/<Site>/Settings, field {64971FA7-F8AC-4C88-9BB2-2949F2A28670}, shown in Pages under Robots → Robots content. Changing robots.txt is a content edit, not a code change.

An empty RobotsContent field does NOT mean "no robots.txt" — it means Disallow: /. Sitecore composes the document server-side when the field is empty and returns a literal User-agent: *\nDisallow: /, which the handler serves as a clean HTTP 200. Every crawler honours it, so a site with an untouched Settings item launches excluded from search while every other check is green. Verified against a live SitecoreAI CM 2026-08-12 across six sites: the five with an empty field all served the blocking document; the one with an authored value served it back verbatim.

Two consequences worth internalising:

  • The SDK's if (!robotsContent) branch is unreachable in practice. It exists to return a 404 when Edge yields nothing, but Edge never yields nothing — it always composes a document. The field is the only control surface, so "we didn't configure it" and "we blocked all crawlers" are the same state.

  • A publish IS required — and the reasoning that said otherwise is the trap worth learning. This bullet previously claimed no publish was needed, on the evidence that preview and live returned byte-identical siteInfo.robots across six sites. The observation was correct; the inference was not. They were identical because every one of those sites had an empty field, so both contexts were serving the same composed default. Identical-when-broken tells you nothing about identical-when-fixed. Re-measured 2026-08-14 immediately after writing the field: preview returned Allow: / while live still returned Disallow: /. The write lands on master, preview Edge follows within seconds, and live Edge does not move until the Settings item is published. This field is subject to the usual preview/live divergence.

    So verify against the live Edge context, never preview — a preview-side check will pass while the public site stays blocked. That is not hypothetical: a fix committed on this evidence read as done for a full day while the live site remained excluded from search.

The default you almost always want:

User-Agent: *
Allow: /

Do not "fix" a blocking robots.txt with a static public/robots.txt. The rewrite would shadow the CMS-managed value and take robots.txt out of the author's reach permanently. Fix RobotsContent on the Settings item.

⚠️ Sitecore auto-appends a Sitemap: line to whatever the field contains, pointing at the CM host (https://xmc-….sitecorecloud.io/sitemap.xml) rather than the site's public domain — observed on every site measured, including correctly-configured ones. Verify it before treating the served robots.txt as production-correct.

Hard Rules

  • Sitemap: src/app/api/sitemap/route.ts — use createSitemapRouteHandler({ client, sites }). Export { GET }. Use sites from .sitecore/sites.json. Set export const dynamic = 'force-dynamic' if the handler relies on request.
  • Robots: src/app/api/robots/route.ts — use createRobotsRouteHandler({ client, sites }). Same pattern.
  • Rewrites: In next.config.ts, add rewrites for /sitemap*.xml and /robots.txt to these route handlers. Use locale: false so they are not localized.
  • Use the same SitecoreClient instance as the rest of the app; do not create a dedicated client for sitemap/robots.
  • Avoid hardcoding the site list; use .sitecore/sites.json.
  • Sitemaps are resolved by host only (no locale in the cache key). A single-language sitemap carries no xhtml:link although xmlns:xhtml is declared, and <loc> uses the CM host when the site has no target hostname (measured 2026-10-02). hreflang in the sitemap depends on the site's alternate-links setting (open). Multi-language SEO: content-sdk-app-router-dictionary-and-i18n.
  • Never ship a static public/robots.txt — it shadows the CMS-managed RobotsContent field and removes robots.txt from authoring control.
  • Before calling a site done, fetch /robots.txt and read the body. Assert 200 and that it does not say Disallow: /. A 200 is not sufficient — the blocking default is served at 200.

Stop Conditions

  • Stop if the user wants to serve sitemap/robots from a different origin or with different auth; document and suggest proxy or edge config.
  • Do not add new env vars for sitemap/robots without documenting them in .env.example.
  • Do not change rewrite paths without updating docs and any references.

References

Content SDK — Theme + Hydration Pattern

Dark+light+system theme in SSR apps has four edges that bite: FOUC, hydration mismatch, lint friction on the canonical patterns, and security tooling that blocks the standard inline-script fixes. This skill captures a working configuration that survives all four.

When to use

  • Adding dark mode / theme toggle to a Content SDK App Router head app.
  • A "Hydration failed because the server rendered HTML didn't match the client" error appears in browser console.
  • "Flash of wrong theme" visible on first paint before React hydrates.
  • ESLint complains about react-hooks/set-state-in-effect in a theme provider.
  • A security hook blocks writing the inline preflight script (the React prop that injects raw HTML strings via a { __html: '...' } object).

How to perform

Five files, all hydration-safe:

1. public/theme-init.js — synchronous preflight (external file, NOT inline)

(function () {
  try {
    var stored = localStorage.getItem('theme');
    var theme = stored === 'light' || stored === 'dark' ? stored : 'system';
    var resolved =
      theme === 'system'
        ? window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
        : theme;
    document.documentElement.classList.toggle('dark', resolved === 'dark');
    document.documentElement.style.colorScheme = resolved;
  } catch (_) {}
})();

2. src/app/layout.tsx — wire it in <head>

<html lang="en" suppressHydrationWarning>
  <head>
    {/* Sync preflight runs before React hydrates — FOUC prevention.
        Parser-blocking is intentional; the rule is a generic perf hint that
        doesn't apply to a 5-line theme preflight. */}
    {/* eslint-disable-next-line @next/next/no-sync-scripts */}
    <script src="/theme-init.js"></script>
  </head>
  <body><ThemeProvider>{children}</ThemeProvider></body>
</html>

3. src/ui/theme-provider.tsx — useSyncExternalStore-based

Uses module-scope subscribe/getSnapshot (NO useEffect for storage reads — that triggers the cascading-render lint). Server snapshot returns 'system' to match the preflight's default. Storage events + matchMedia trigger re-renders.

4. src/ui/theme-toggle.tsx — mounted-flag for active state

const [mounted, setMounted] = useState(false);
// Canonical SSR-safe "after hydration" flag — setState-in-effect IS the
// pattern; useSyncExternalStore gives us `theme`, this flag separately
// guards client-only styling like "which button is active right now."
// eslint-disable-next-line react-hooks/set-state-in-effect
useEffect(() => setMounted(true), []);
// ...
const active = mounted && theme === opt.value;

5. src/app/globals.css — Tailwind v4 token model

@import "tailwindcss";

@theme {
  --color-canvas: #fafaf7;
  --color-ink: #0c0c14;
  /* ... */
}

@custom-variant dark (&:where(.dark, .dark *));

.dark {
  --color-canvas: #0c0c14;
  --color-ink: #f4f4ef;
  /* ... */
}

:root { color-scheme: light; }
.dark { color-scheme: dark; }

Hard Rules

  • NEVER use React's inline raw-HTML injection prop for the preflight script — the one that takes a { __html: '...' } object and writes the string into the element. Security tooling blocks it (false-positive XSS warning). Use a real file in public/ referenced via <script src>. Same end-result (parser-blocking sync execution), no hook trip.
  • The preflight script's algorithm must match theme-provider.tsx exactly. If they diverge, the first paint and the first React render will disagree. Keep them in sync; treat them as one logical unit.
  • useSyncExternalStore for theme reads, NOT useEffect + setState. The cascading-render lint fires on the latter; the former is the React 19 canonical pattern for browser-API subscriptions.
  • Server snapshot returns 'system' always. Matches the preflight's default-when-no-localStorage. If you return anything else server-side, you'll get a hydration mismatch on the very first paint.
  • Mounted-flag pattern is unavoidable for components whose visible state depends on client-only data. Examples: active-button highlight, "current theme" label, time-of-day greeting. Accept the one-frame visual delay; that's the cost of SSR safety. Disable react-hooks/set-state-in-effect on the useEffect(() => setMounted(true), []) call with an inline comment.
  • suppressHydrationWarning only silences the <html> element's own attribute mismatch. It does NOT suppress mismatches in children. Fix child mismatches with the mounted-flag pattern.
  • Apply .dark class to <html>, not <body>. That's where the preflight applies it and where color-scheme should sit.
  • Atoms (beta.atoms) compile dark: at runtime to prefers-color-scheme unless globals.css declares @custom-variant dark, which this pattern does (content-sdk-app-router-atoms § 7).
  • Tailwind v4 doesn't have tailwind.config.js. All token + variant config goes in globals.css via @theme, @custom-variant, etc.

Stop Conditions

  • If hydration warnings persist after applying this pattern, look for OTHER components that branch on browser globals (typeof window, navigator, matchMedia) in their render body. The theme system is not the only source.
  • If FOUC persists, verify the preflight script is in <head> BEFORE <body> and is NOT marked async or defer. Both attributes break parser-blocking.
  • Don't replace useSyncExternalStore with a custom useEffect+useState because of lint friction — that path leads back to the hydration bug.

The toggle visibility env gate

If the design system says theme toggles should be hidden in some environments (e.g., embedded mode), gate ONLY the toggle's render, not the provider:

const showToggle = process.env.NEXT_PUBLIC_SHOW_THEME_TOGGLE !== 'false';
// ...
{showToggle ? <ThemeToggle /> : null}

The provider always mounts so the theme is applied; just the UI surface is conditional.

Verification

  • Hard-refresh the page in light, dark, and system modes. No flash, no console warnings.
  • Open browser devtools, check <html>'s class — .dark matches the resolved theme on first paint.
  • Toggle theme → DOM updates instantly. Refresh → choice persists. Set to "system" → OS-level dark mode change propagates without refresh.
  • npm run lint clean.

Related

  • content-sdk-app-router-component-scaffold — for the component file structure context.
  • content-sdk-component-naming-traps — for where the UI infrastructure (src/ui/) should live.

References

Content SDK Troubleshoot Editing (App Router)

This skill focuses on diagnosing editing, preview, and design library issues. For implementing editing-safe rendering (draftMode, getPreview/getDesignLibraryData, API routes), use the content-sdk-app-router-editing-safe-rendering skill; the two are complementary (implementation vs. troubleshooting).

Diagnose and fix editing, preview, and design library issues without breaking the single client or proxy order. This app uses draftMode() and searchParams for preview data.

When to use

  • User reports that editing, preview, or design library is broken or inconsistent.
  • Task involves debugging "not working in editor," missing chromes, or wrong data in preview.
  • User mentions "editing broken," "preview not working," "design library," or "editor issues."

How to perform

  • Confirm draftMode() and searchParams-based getPreview/getDesignLibraryData; ensure setRequestLocale is called at the top of the page. Verify editing API routes are not rewritten (check proxy matcher) and both component maps include the component. Check env (editingSecret, API config) and .env.example documentation.

Hard Rules

  • Preview flow: Use draftMode() in Server Components; when enabled, use client.getPreview(editingParams) or client.getDesignLibraryData(editingParams) from searchParams. Ensure site/locale are passed correctly (e.g. from route params or editingParams).
  • next-intl: Ensure setRequestLocale(\${site}_${locale}`)` is called at the top of the page; missing setRequestLocale can cause locale or dictionary issues in editor.
  • Editing API routes (src/app/api/editing/config/route.ts, editing/render/route.ts) must be reachable and use the same component maps (component-map.ts and component-map.client.ts) and config as the app. Check matcher in proxy.ts so /api/editing is not rewritten or blocked.
  • Check that both component maps include all components used in the layout; missing registration causes "component not found" in editor.
  • Environment: editingSecret and API config must be set (in env); document in .env.example only. Do not log or commit secrets.
  • Symptom: Pages shows a German body but English labels and <html lang="en"> → the editing render takes [locale] from route, not sc_lang (measured 2026-10-02); see content-sdk-app-router-dictionary-and-i18n § 8.
  • Design Library library-low-code mode / atoms:* events (beta.atoms only) → content-sdk-app-router-atoms.

Stop Conditions

  • Stop if the fix would require changing CI, deployment, or SitecoreAI project settings; suggest the user do that and document the required env or config.
  • Stop if the issue might be in Sitecore (layout, template) rather than the app; suggest checking layout and content in SitecoreAI.
  • Do not recommend disabling security (e.g. skipping secret validation) without explicit user request and warning.

References

Sponsors

Details

Marketplace
Chris1415/sitecore-skills-pocs
Source
plugins/sitecore-content-sdk-nextjs-app-router
Category
Sitecore
License
Apache-2.0

More from Chris1415/sitecore-skills-pocs

All 8