
sitecore-content-sdk-nextjs-pages-router
Content SDK skills for Next.js Pages Router head apps. Install with 'Sitecore Content SDK - Core'.
- version
- 0.7.0
- GitHub stars
- 12
Install
/plugin install sitecore-content-sdk-nextjs-pages-router@sitecore-skills-pocsRun it inside Claude Code after adding the marketplace with /plugin marketplace add Chris1415/sitecore-skills-pocs.
Contents
Discovered from sourceSkills 11
Content SDK Component Data Strategy (Pages Router)
This app uses getComponentData. After getPage, use client.getComponentData(page.layout, context, components) to resolve component props and pass the result to the layout renderer. All Sitecore-driven component data goes through this flow.
When to use
- User asks how to pass data to components, wire component props, or integrate custom/BYOC components.
- Task involves getComponentData, component props, or BYOC.
- User mentions "component data," "props," "BYOC," or "getComponentData."
How to perform
- In [[...path]].tsx: getPage(path, { locale: context.locale }), then getDictionary, then getComponentData(page.layout, context, components). Return props to Layout; do not fetch in _app or in child components. Register BYOC in .sitecore/component-map.ts; getComponentData passes resolved props.
Hard Rules
- Flow in catch-all page: In getStaticProps/getServerSideProps: (1)
client.getPage(path, { locale: context.locale }), (2)client.getDictionary({ site: page.siteName, locale: page.locale }), (3)client.getComponentData(page.layout, context, components)to resolve component props. Return{ props: { page, dictionary, componentProps }, notFound: !page }. Pass these props to Providers and Layout; do not fetch Sitecore data in _app. - Do not fetch per-component data in parallel outside this flow unless the app pattern explicitly does so. All Sitecore-driven component data goes through getComponentData.
- Single client instance; do not create a new client inside components. The client is used in getStaticProps/getServerSideProps and in API routes.
- BYOC or custom components: Must be registered in
.sitecore/component-map.tsand receive props in the shape the layout expects (e.g. fields, params). getComponentData will pass the resolved props. - Do not fetch layout or page data inside a child component (e.g. another getPage call); fetch at the catch-all page level and pass props via getComponentData and layout.
Stop Conditions
- Stop if the user wants to fetch page/layout data inside a child component; recommend fetching in [[...path]].tsx and passing via getComponentData and layout.
- Do not duplicate getComponentData or getPage logic across components; keep data fetching in the catch-all page only.
- Do not fetch Sitecore data in _app; all data flows from [[...path]].tsx.
References
content-sdk-pages-router-graphql-data-fetchingskill and Content SDK skills overview for getPage, getComponentData, and data flow.- Official Content SDK docs.
Content SDK Component Registration (Pages Router)
Register components in the Sitecore component map so the layout and editing pipeline can resolve and render them. This app has a single map: .sitecore/component-map.ts.
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. - User asks how to register a component or fix component resolution.
How to perform
- The map is GENERATED, not hand-written.
.sitecore/component-map.tsis produced fromsrc/components/bysitecore-tools project component generate-map, which the scaffold wires into bothnpm run devandnpm run build, plus a--watchvariant during dev. So the normal way to register a component is to create the file insrc/components/and re-run dev/build. - Refresh manually with
npm run sitecore-tools:generate-map. Edit the map by hand only when the generator genuinely cannot express your case — and expect the nextdev/buildto overwrite it. The map is consumed by getComponentData and the editing API routes; keys must match the layoutcomponentName.
Worked example
Pages Router has ONE map (no component-map.client.ts) and no componentType: 'client' split. The key is the layout componentName (case-sensitive); each entry spreads the imported module.
// .sitecore/component-map.ts — the single Pages Router map
import { NextjsContentSdkComponent } from '@sitecore-content-sdk/nextjs';
import * as Promo from 'src/components/Promo/Promo';
export const componentMap = new Map<string, NextjsContentSdkComponent>([
// ...built-ins from the scaffold (BYOCWrapper, FEaaSWrapper, Form) stay as-is...
['Promo', { ...Promo }],
]);
export default componentMap;
This map is consumed by getComponentData(page.layout, context, components) in src/pages/[[...path]].tsx and by the editing API routes (src/pages/api/editing/config.ts, render.ts, feaas/render.ts). A wrong/missing key renders <MissingComponent>.
Hard Rules
- Every component rendered from Sitecore layout must be registered in
.sitecore/component-map.ts— but achieve that by runningnpm run sitecore-tools:generate-map(or justnpm run dev/npm run build), not by editing the map. Do not hand-edit generated entries unless the generator cannot handle the case. - 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.
- The map is used by
getComponentData(page.layout, context, components)in the catch-all page and by editing API routes (src/pages/api/editing/config.ts,render.ts,feaas/render.ts). - Use consistent component names (same key in map as used in layout). Follow existing naming in the map.
- Do not remove or rename registrations without updating all references (layout, getComponentData, editing routes).
Stop Conditions
- Stop if modifying the component map would break existing layout or editing; suggest a safe change or ask for confirmation.
- Do not edit
.sitecore/metadata.jsonor import-map unless the task explicitly requires it.
References
Content SDK Component Scaffold (Pages Router)
Scaffold new Sitecore components so they integrate with the layout and editing pipeline. This app uses Pages Router with a single component map.
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. - Do not register it by hand.
.sitecore/component-map.tsregenerates fromsrc/components/duringnpm run devandnpm run build; runnpm run sitecore-tools:generate-mapto refresh it on demand (see thecontent-sdk-pages-router-component-registrationskill). - Run
npm run buildto verify, then confirm the component appears in the map.
Worked example
Pages Router has no Server/Client split — one component shape, one map, no 'use client' map routing. Value components (Text/Image/Link) and field types import from @sitecore-content-sdk/nextjs. Convention: src/components/<Name>/<Name>.tsx.
// src/components/Promo/Promo.tsx
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 */}
{fields?.Cta && <Link field={fields.Cta} />}
</section>
);
export default Promo;
Props are resolved by getComponentData(page.layout, context, components) in the catch-all page (see content-sdk-pages-router-component-data-strategy), then register in the single .sitecore/component-map.ts.
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/reactor the app's types. - Export a single default component; one component per file unless the app pattern differs.
- Prefer
npm run sitecore-tools:generate-mapover hand-editing the map; register manually only when the generator cannot handle the change, and expect the nextdev/buildto overwrite it. - The component is not done until it appears in
.sitecore/component-map.tsafter regeneration (see thecontent-sdk-pages-router-component-registrationskill). Pages Router has a single map, used by getComponentData and the editing API routes.
Stop Conditions
- Do not create components in
.next/,node_modules/, or build output.
References
Content SDK Component Variants (Pages Router)
One component definition can have multiple presentations or data-driven variants. Component props are resolved by getComponentData(page.layout, context, components); keep registration and layout aligned.
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 uses one key per variant. Use layout/fields/params for variant; register in
.sitecore/component-map.ts. getComponentData resolves props; align with existing app convention.
Worked example
The SDK variant mechanism is identical to App Router: params.FieldNames resolves to a named export, case-sensitive; generate-map merges variant files (<Name>.<Variant>.tsx) into one map entry. The only Pages-Router difference is that props arrive via getComponentData, and registration is the single .sitecore/component-map.ts.
// 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 — generate-map merges variant exports under one componentName
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 }],
]);
Resolution: FieldNames: "Card" → component.Card; empty / missing / "Default" → component.default; unmatched name → <MissingComponent> + console warning. Each variant also needs a CMS Headless Variant item for the Pages dropdown. Full contract: 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. getComponentData passes the layout-driven props to the component.
- Register in
.sitecore/component-map.tsonly. If the app uses one key per variant, register each; if one key with variant param, single registration. Follow existing app convention. - Keep the map in sync via
npm run sitecore-tools:generate-map(it also runs onnpm run dev/npm run build) rather than editing it — the generator merges every<Name>.<Variant>.tsxexport 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 Dictionary and i18n (Pages Router)
This app uses Next.js built-in i18n. There is no [locale] in the URL path; locale is provided by Next.js as context.locale in getStaticProps/getServerSideProps.
When to use
- User asks to add or change translated content, locale, or dictionary.
- Task involves getDictionary, Next.js i18n, or context.locale.
- User mentions "dictionary," "i18n," "locale," or "translation."
How to perform
- Locales:
next.config.js→ i18n.locales, defaultLocale. In getStaticProps/getServerSideProps use context.locale; after getPage use client.getDictionary({ site: page.siteName, locale: page.locale }). Use a single getDictionary per request. Do not assume locale from headers.
Hard Rules
- Config:
next.config.js→i18n.localesandi18n.defaultLocale. Match (or subset) Sitecore languages. - Per-request locale: Use
context.localein getStaticProps and getServerSideProps. Pass it toclient.getPage(path, { locale: context.locale }). After fetching the page, usepage.siteNameandpage.locale(orcontext.locale) forclient.getDictionary({ site: page.siteName, locale: page.locale })and for getComponentData. - Align locales in next.config.js with Sitecore languages (e.g. from sitecore.config.ts defaultLanguage). Use a single client.getDictionary per request for the active site/locale.
- Do not assume locale from headers or a different source; always use
context.localeand the page's site/locale for Sitecore calls.
Stop Conditions
- Stop if adding a new locale without confirming it exists in Sitecore and in next.config.js i18n.
- Do not duplicate dictionary fetching without a clear need; prefer one fetch per request in the catch-all page.
References
Content SDK Editing-Safe Rendering (Pages Router)
Ensure components behave correctly in SitecoreAI editing, preview, and design library. This app uses context.preview and context.previewData in getStaticProps/getServerSideProps 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 [[...path]].tsx getStaticProps/getServerSideProps: check context.preview; when true use isDesignLibraryPreviewData(context.previewData) to choose getDesignLibraryData vs getPreview; otherwise getPage + getDictionary + getComponentData. Editing routes: config uses EditingConfigMiddleware, render uses EditingRenderMiddleware, feaas/render uses FEAASRenderMiddleware; export handler as default.
Hard Rules
- In the catch-all page (
src/pages/[[...path]].tsx), usecontext.previewandcontext.previewData. When in preview, useisDesignLibraryPreviewData(context.previewData)to distinguish: if true, useclient.getDesignLibraryData(context.previewData); otherwise useclient.getPreview(context.previewData). When not in preview, usegetPage(path, { locale: context.locale })then getDictionary and getComponentData as usual. - Do not assume editing/preview context in components that might run in static or non-editing contexts; guard on context.preview in getStaticProps/getServerSideProps.
- Editing API routes:
src/pages/api/editing/config.tsusesEditingConfigMiddleware({ components, metadata }).getHandler()(import components from.sitecore/component-map, metadata from.sitecore/metadata.json).src/pages/api/editing/render.tsusesEditingRenderMiddleware().getHandler().src/pages/api/editing/feaas/render.tsusesFEAASRenderMiddleware().getHandler(). Export the handler as default. Do not duplicate client creation; config uses the same component map as the app. - Never commit editing secrets; use environment variables and document in .env.example only.
- 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:
- Any component:
const { page } = useSitecore(); const isEditing = page.mode.isEditing;(useSitecorefrom@sitecore-content-sdk/nextjs; needsSitecoreProviderin the tree — the scaffold provides it). Pages Router has no React Server Components, so every component may use the hook.useSitecore()is the unified hook; there is nouseSitecoreContextin Content SDK. - Router-agnostic alternative (no hook): a field is in editing context iff
field.metadatais present —const isEditing = !!fields?.SomeTextField?.metadata;. Sitecore emitsfield.metadataonly in edit/preview.TextField/RichTextField extends FieldMetadata;ImageField/LinkFieldcarry metadata only via& FieldMetadata, so read editing off a text field. Useful for shared code that also targets App Router server components.
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; // router-agnostic 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-pages-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 context.previewData.
- Do not recommend disabling secret validation without explicit user request and warning.
References
Content SDK GraphQL Data Fetching (Pages Router)
All Sitecore data fetching goes through the single client in src/lib/sitecore-client.ts. Use getPage, getDictionary, and getComponentData in the catch-all page. Path from extractPath(context); locale from context.locale.
When to use
- User asks how to fetch page data, layout, or dictionary phrases.
- Task involves getPage, getDictionary, getComponentData, getPreview, getDesignLibraryData, or getPagePaths.
- User mentions "sitecore client," "Layout Service," "page data," or "dictionary."
How to perform
- Use the client from
src/lib/sitecore-client.tsonly. In [[...path]].tsx: useextractPath(context)andcontext.locale; call getPage(path, { locale: context.locale }), then getDictionary and getComponentData(page.layout, context, components). For SSG use getPagePaths in getStaticPaths. For preview use context.preview and getPreview/getDesignLibraryData(context.previewData).
Hard Rules
- Use the single SitecoreClient instance in
src/lib/sitecore-client.ts. Do not create a second client or instantiate SitecoreClient elsewhere. - Path and locale: Use
extractPath(context)(from@sitecore-content-sdk/nextjs/utils) to get the path array; usecontext.localefor locale. Do not assume path or locale from elsewhere. - Catch-all page flow: In getStaticProps/getServerSideProps:
client.getPage(path, { locale: context.locale }), thenclient.getDictionary({ site: page.siteName, locale: page.locale })andclient.getComponentData(page.layout, context, components)for component props. Pass the result to the layout renderer. - SSG: In getStaticPaths, use
client.getPagePaths(siteNames, context?.locales || [])where site names come from.sitecore/sites.json(e.g.sites.map((s) => s.name)). Userevalidatein getStaticProps for ISR. - Preview: Use
context.previewandcontext.previewData; when in preview, useclient.getPreview(context.previewData)orclient.getDesignLibraryData(context.previewData). - 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.
- Do not fetch in _app; all data flows from [[...path]].tsx.
References
Content SDK Multisite Management (Pages Router)
Site resolution from request (e.g. hostname or cookie); proxy rewrites to internal path. No [locale] in URL; Next.js i18n handles locale separately.
When to use
- User asks about multiple sites, hostnames, or site resolution.
- Task involves .sitecore/sites.json, multisite config, or proxy/middleware for site.
- User mentions "multisite," "site resolution," "hostname," or "sites.json."
How to perform
- Site list:
.sitecore/sites.json. Proxy insrc/proxy.ts; ensuresrc/middleware.tsre-exports it if present. Keep chain order: MultisiteProxy → RedirectsProxy → PersonalizeProxy. Exclude /api, _next, static assets in matcher/skip.
Hard Rules
- Site list is in
.sitecore/sites.json(typically generated by Sitecore CLI or deployment). Avoid hand-editing unless the format is known. - Proxy: Implemented in
src/proxy.ts. Next.js runs middleware frommiddleware.tsat root or insrc/— if the app only hasproxy.ts, addsrc/middleware.tsthat re-exports it. - Chain order is fixed: MultisiteProxy → RedirectsProxy → PersonalizeProxy. Do not change this order. MultisiteProxy resolves site from request (hostname or cookie) and rewrites; redirects and personalization run after.
- Skip / matcher: Use the skip callback and matcher to exclude /api, /_next, static files, and health checks so the proxy stays lightweight.
- Config: sitecore.config.ts → multisite (e.g. enabled, useCookieResolution). Single SitecoreClient; pass resolved site (and locale from context.locale) into getPage, getDictionary, getComponentData.
Stop Conditions
- Stop if the user wants to reorder the proxy chain; explain that order is required.
- 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 (Pages Router)
Single catch-all route; no [site] or [locale] in the URL path. Site is resolved by middleware; locale from Next.js i18n (context.locale).
When to use
- User asks to change routing, add a route, or fix 404/500 behavior.
- Task involves catch-all route, placeholders, _app, or Layout.tsx.
- User mentions "[[...path]]," "placeholder," "layout," or "getStaticProps."
How to perform
- Single Sitecore page:
src/pages/[[...path]].tsx. UseextractPath(context)for path andcontext.localefor locale. Fetch all data in getStaticProps/getServerSideProps and pass to _app and Layout. Not-found/error: use getErrorPage in getStaticProps or 404.tsx / _error.tsx as appropriate.
Hard Rules
- Single Sitecore page:
src/pages/[[...path]].tsx. This is the only page that renders Sitecore content. Do not add another page or catch-all for Sitecore content. - Path: Use
extractPath(context)(from@sitecore-content-sdk/nextjs/utils) to get the path array. Locale: Usecontext.locale(Next.js i18n). Do not assume path or locale from headers or elsewhere. - Data flow: All Sitecore data is fetched in getStaticProps/getServerSideProps in [[...path]].tsx and passed to _app and Layout. Do not fetch Sitecore data in _app.tsx.
- Layout: Layout.tsx renders page layout and placeholders; Providers wrap component props and page context; Bootstrap handles site name and preview mode.
- Placeholders are rendered by the layout; do not change placeholder names or structure without aligning with Sitecore layout definition.
- 404 / 500 / _error: When the catch-all returns
notFound: true, Next.js renders 404.tsx. For Sitecore-driven error content useclient.getErrorPage(ErrorPage.NotFound)orErrorPage.InternalServerErrorin getStaticProps when applicable. _error.tsx is the error boundary; it does not fetch from Sitecore.
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 proxy/middleware order; order is fixed (MultisiteProxy → RedirectsProxy → PersonalizeProxy).
- Do not move or rename the catch-all file without updating all references.
References
Content SDK Sitemap and Robots (Pages Router)
Sitemap and robots.txt are served via API routes and rewrites. Use the SDK middleware getHandler pattern 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/pages/api/sitemap.tswithSitemapMiddleware(scClient, sites).getHandler(); robots:src/pages/api/robots.tswithRobotsMiddleware(scClient, sites).getHandler(). Use sites from.sitecore/sites.json. Add rewrites in next.config.js for /sitemap*.xml and /robots.txt to these API routes.
Where robots.txt content actually comes from
The middleware serves nothing of its own — the body is CMS content. RobotsMiddleware 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. This is identical in App Router; only the handler wrapper differs.
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 middleware 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.robotsacross 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 returnedAllow: /while live still returnedDisallow: /. 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/pages/api/sitemap.ts— usenew SitemapMiddleware(scClient, sites).getHandler(). Export the handler. Usesitesfrom.sitecore/sites.json. - Robots:
src/pages/api/robots.ts— usenew RobotsMiddleware(scClient, sites).getHandler(). Same pattern. - Rewrites: In
next.config.js, add rewrites for/robots.txtand/sitemap*.xmlto the corresponding API routes (e.g./sitemap.xml→/api/sitemap). - Use the same SitecoreClient instance (e.g. from
src/lib/sitecore-client.ts) as the rest of the app; do not create a dedicated client for sitemap/robots. - Avoid hardcoding the site list; use .sitecore/sites.json.
- Never ship a static
public/robots.txt— it shadows the CMS-managedRobotsContentfield and removes robots.txt from authoring control. - Before calling a site done, fetch
/robots.txtand read the body. Assert 200 and that it does not sayDisallow: /. 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 Troubleshoot Editing (Pages Router)
This skill focuses on diagnosing editing, preview, and design library issues. For implementing editing-safe rendering (context.preview, getPreview/getDesignLibraryData, API routes), use the content-sdk-pages-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 context.preview and context.previewData in getStaticProps/getServerSideProps.
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 context.preview and context.previewData and correct path/locale (extractPath, context.locale). Verify editing API routes (config, render, feaas/render) are not rewritten (check proxy matcher) and component-map.ts includes the component. Check env (editingSecret, API config) and .env.example documentation.
Hard Rules
- Preview flow: In [[...path]].tsx getStaticProps/getServerSideProps, use
context.previewandcontext.previewData. When in preview, useclient.getPreview(context.previewData)orclient.getDesignLibraryData(context.previewData). Ensure path and locale come from extractPath(context) and context.locale when not in preview. - Editing API routes:
src/pages/api/editing/config.ts(EditingConfigMiddleware),render.ts(EditingRenderMiddleware),feaas/render.ts(FEAASRenderMiddleware) must be reachable and use the same component map (.sitecore/component-map.ts) and config as the app. Check proxyconfig.matcherso/apiis excluded and not rewritten or blocked. - Check that the component map includes 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.
- Common causes: wrong path/locale passed to getPreview/getDesignLibraryData, or component not registered in component-map.ts.
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
content-sdk-pages-router-editing-safe-renderingskill and Content SDK skills overview for preview and editing flow.- Official Content SDK docs.
Sponsors
Details
- Marketplace
- Chris1415/sitecore-skills-pocs
- Source
- plugins/sitecore-content-sdk-nextjs-pages-router
- Category
- Sitecore
- License
- Apache-2.0