
sitecore-marketplace
Sitecore Marketplace SDK: client, xmc and ai references, app lifecycle, extension routes, testing and debugging, host-frame visual testing. Scaffolds are in sitecore-setup.
- version
- 0.8.0
- GitHub stars
- 12
Install
/plugin install sitecore-marketplace@sitecore-skills-pocsRun it inside Claude Code after adding the marketplace with /plugin marketplace add Chris1415/sitecore-skills-pocs.
Contents
Discovered from sourceSkills 7
Sitecore Marketplace AI Skills SDK
When to use
- The project uses
@sitecore-marketplace-sdk/ai - The PRD mentions brand review, AI-assisted content compliance, or "AI skills"
- The architecture calls for LLM-powered checks grounded in SitecoreAI data (brand kits, content)
- You're evaluating whether to use the module mode (inside a Client SDK app) or the experimental direct mode (server-to-server)
For auth setup (Auth0, iframe cookies, orgId/tenantId) see the marketplace-sdk-lifecycle skill, § 5.
For core Client SDK (query/mutate/subscribe, extension points) see the marketplace-sdk-client skill.
For XMC endpoints see the marketplace-sdk-xmc skill.
1. Package overview
| Package | Purpose |
|---|---|
@sitecore-marketplace-sdk/ai | Type-safe access to AI skills APIs — LLM capabilities grounded in SitecoreAI data |
Install (always latest): npm install @sitecore-marketplace-sdk/ai@latest
Status: interfaces marked experimental_* may change between releases. Currently exposes a single skill — generateBrandReview — with more skills expected.
2. Two usage modes
The AI package supports two initialization patterns, chosen by where your code runs:
| Mode | When | Init function | Call shape | Token handling |
|---|---|---|---|---|
| A. Module mode | Inside a Client SDK iframe app (architectures 4a/4b in the marketplace-sdk-lifecycle skill) | ClientSDK.init({ modules: [AI, …] }) | client.mutate('ai.skills.*', …) | Portal brokers via postMessage — you hold no token |
| B. Experimental direct | Standalone / server-to-server (architecture 4c in the marketplace-sdk-lifecycle skill) | experimental_createAIClient({ getAccessToken }) | ai.skills.*(…) | You supply an Auth0 access token via getAccessToken |
Pick one per app. Mixing is rarely needed and adds auth complexity. If the app already uses the Client SDK for XMC queries, use Mode A. If it runs outside the iframe (cron, background jobs, microservices), use Mode B.
3. Mode A — AI as a Client SDK module
3a. Registration
import { ClientSDK } from '@sitecore-marketplace-sdk/client';
import { XMC } from '@sitecore-marketplace-sdk/xmc';
import { AI } from '@sitecore-marketplace-sdk/ai';
const client = await ClientSDK.init({
target: window.parent,
modules: [XMC, AI], // register both — they coexist
});
Both modules can be registered together. Keys get prefixed: xmc.* for XMC, ai.* for AI.
3b. Calling a skill (mutation)
const result = await client.mutate('ai.skills.generateBrandReview', {
params: {
body: {
brandkitId: 'your-brandkit-id',
input: {
headline: 'Summer Sale — 50% Off Everything!',
body: 'Shop our biggest sale of the year.',
},
},
query: { sitecoreContextId }, // pass it; see § 9b
},
});
Critical — params: wrapper is mandatory (verified live 2026-04-22). Mode A mutate calls through the Client SDK wrap hey-api options one level deeper than Mode B direct calls: { params: { body, query, path?, headers? } }, NOT flat { body, query }. Writing flat fails tsc --noEmit with:
TS2353: Object literal may only specify known properties, and 'body' does not exist in type 'MutationOptions<"ai.skills.generateBrandReview">'.
Same hey-api convention as XMC mutations (the marketplace-sdk-xmc skill, § 3). Easy to miss because sdk.generateBrandReview(options) signature in sdk.gen.d.ts reads flat — that's the Mode B shape. Mode A wraps it.
sitecoreContextId rule: technically optional in Mode A per the type, but always pass it — the contract is the same as every other xmc.* call documented in the marketplace-sdk-xmc skill, § 6a. Use the requireContextId() helper from the marketplace-sdk-client skill, § 4.
Live-verified response shape (2026-04-22): .data unwraps to Array<SectionReview> with at least sectionId, score, reason fields populated per entry. Example:
{
data: [
{
sectionId: '<section-id>',
score: 1, // 1–5
reason: 'The provided image lacks sufficient detail to demonstrate alignment with the mandatory brand-kit requirements…',
// additional SectionReview fields (fieldReviews, etc.) present when sections are targeted
},
// …one entry per reviewed section
],
}
4. Mode B — experimental direct client
4a. Create the client
import { experimental_createAIClient } from '@sitecore-marketplace-sdk/ai';
const ai = await experimental_createAIClient({
getAccessToken: async () => {
// Return an Auth0 access token with the right audience/scopes.
// See the marketplace-sdk-lifecycle skill, § 5, for Auth0 config.
return await getUserAccessToken();
},
});
getAccessToken is called on every request — fetch from session / refresh as needed. Do not return an expired token; the function can (and should) be async.
4b. Calling a skill
const brandReview = await ai.skills.generateBrandReview({
body: {
brandkitId: 'your-brandkit-id',
input: {
headline: 'Your marketing headline',
body: 'Your marketing body copy',
},
},
query: { sitecoreContextId: 'your-context-id' }, // REQUIRED in Mode B
});
4c. Getting sitecoreContextId for Mode B
In Mode B you need a sitecoreContextId per request. Capture it once with a small Client SDK standalone page:
// One-time capture in a Client SDK app
const appCtx = await client.query('application.context');
const contextId = appCtx.data?.resourceAccess?.[0]?.context?.live
?? appCtx.data?.resourceAccess?.[0]?.context?.preview;
// Persist contextId in your server-side config
Then pass it in every experimental_* call. See the marketplace-sdk-lifecycle skill, § 5c, for the orgId / tenantId companions.
4d. Required env vars (Mode B)
Same env vars as any Mode B module — AUTH0_DOMAIN, AUTH0_AUDIENCE, AUTH0_SCOPE, SITECORE_ORGANIZATION_ID, SITECORE_TENANT_ID. Full values and where to capture them: the marketplace-sdk-lifecycle skill, § 5b + § 5c. Mandatory Auth0Client cookie block: the marketplace-sdk-testing-debug skill, § 4a.
5. AI Skills API reference
5a. generateBrandReview
Runs input content against a brand kit using an LLM and returns compliance scores, explanations, and fix suggestions. The brand kit defines tone-of-voice, visual identity, and other sections; the review scores how well the input matches.
Signature — Mode A wraps, Mode B does not (verified live 2026-04-22):
// Mode A — via client.mutate (hey-api double-wrap)
{
params: {
body: GenerateBrandReviewBody;
query?: { sitecoreContextId: string };
headers?: { 'x-sc-feature'?: string; /* … */ };
};
}
// Mode B — via experimental_createAIClient (flat hey-api options)
{
body: GenerateBrandReviewBody;
query: { sitecoreContextId: string }; // REQUIRED in Mode B
}
// Shared body shape
type GenerateBrandReviewBody = {
brandkitId: string;
input: Record<string, InputValue>;
sections?: Array<{
sectionId: string;
fieldIds?: string[];
}> | null;
};
Where InputValue (from the SDK's GenerateBrandReviewModelRequest["input"] union) is one of:
string— live-confirmed as a first-class pattern (2026-04-22): pass short copy, tone guidelines, prompt snippets as raw strings under arbitrary keys. NoExtractableFilewrapping required. Example:{ brandVoice: "Our brand voice is warm, confident, and direct." }.number,boolean,nullArray<unknown>,Record<string, unknown>(structured content)ExtractableFile(file-based content — see § 6)Array<ExtractableFile>
Response: .data unwraps to Array<SectionReview>. One entry per reviewed section with sectionId, score (1–5), reason. Additional fields populated when sections targeting is used.
Default behavior: all brand-kit sections are reviewed. Use sections to target specific sections / field IDs.
6. ExtractableFile — sending images and documents
Use when the content under review is a file rather than plain text.
6a. Common shape
interface ExtractableFile {
name: string;
type: 'image' | 'document';
url: string; // HTTPS URL, or a data: URL (base64)
mimeType: string; // see per-type tables below
detail?: 'low' | 'auto' | 'high'; // images only — controls LLM processing depth
auth?: {
authType: 'bearer' | 'basic' | 'custom';
value: string; // token, username:password base64, or header value
customHeaderName?: string; // required when authType === 'custom'
};
}
6b. Images
mimeType | Accepted |
|---|---|
image/jpeg | yes |
image/png | yes |
image/webp | yes |
input: {
heroImage: {
name: 'hero-banner.png',
type: 'image',
url: 'https://cdn.example.com/hero-banner.png',
mimeType: 'image/png',
detail: 'high',
},
}
Base64 inline variant:
logo: {
name: 'logo.png',
type: 'image',
url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA…',
mimeType: 'image/png',
detail: 'auto',
}
6c. Documents
mimeType | Accepted |
|---|---|
application/pdf | yes |
text/plain | yes |
input: {
pressRelease: {
name: 'press-release.pdf',
type: 'document',
url: 'https://example.com/press-release.pdf',
mimeType: 'application/pdf',
},
}
6d. Auth for protected files
If the url needs auth to download:
internalDoc: {
name: 'style-guide.pdf',
type: 'document',
url: 'https://internal.example.com/style-guide.pdf',
mimeType: 'application/pdf',
auth: {
authType: 'bearer',
value: 'your-file-access-token',
},
}
authType options:
'bearer'→Authorization: Bearer <value>'basic'→Authorization: Basic <value>(value is base64user:pass)'custom'→<customHeaderName>: <value>
6e. Mixed input
input is a flexible record — combine text, images, and documents in one request:
input: {
headline: 'Summer Sale — 50% Off Everything!',
body: 'Shop our biggest sale of the year.',
banner: { name: 'summer-banner.webp', type: 'image', url: '…', mimeType: 'image/webp', detail: 'high' },
campaign: { name: 'brief.pdf', type: 'document', url: '…', mimeType: 'application/pdf' },
productPhotos: [
{ name: 'front.jpg', type: 'image', url: '…', mimeType: 'image/jpeg' },
{ name: 'back.jpg', type: 'image', url: '…', mimeType: 'image/jpeg' },
],
wordCount: 150,
tags: ['summer', 'sale'],
}
7. Targeting specific brand-kit sections
By default all sections are reviewed. Narrow with sections:
sections: [
{ sectionId: 'tone-of-voice', fieldIds: ['headline', 'body'] },
{ sectionId: 'visual-identity' }, // whole section
]
- Omit
fieldIdsto evaluate the whole section. - Use when you only want scores for specific dimensions (e.g. tone, not visual).
8. Type imports (Mode B)
For better IntelliSense in Mode B:
import {
experimental_Skills,
} from '@sitecore-marketplace-sdk/ai';
const request: experimental_Skills.GenerateBrandReviewModelRequest = {
brandkitId: 'your-brandkit-id',
input: { headline: 'Your headline' },
};
const file: experimental_Skills.ExtractableFile = {
name: 'banner.png',
type: 'image',
url: 'https://example.com/banner.png',
mimeType: 'image/png',
};
const contentType = experimental_Skills.ContentType.SHORT_TEXT;
9. Common pitfalls
9a. Wrong mode for the runtime
Client-side browser code that uses experimental_createAIClient with a user access token will leak the token through the network tab and violate iframe cookie rules. For iframe apps always use Mode A. Mode B is for server routes, cron jobs, microservices.
9b. Missing sitecoreContextId — always pass it
Mode B types mark query.sitecoreContextId as required; Mode A types mark it optional. Always pass it in both modes — same rule as every xmc.* call (the marketplace-sdk-xmc skill, § 6a). Without it, responses may silently land on the wrong environment. Use the requireContextId() helper from the marketplace-sdk-client skill, § 4, to narrow from application.context.resourceAccess[] without the as string anti-pattern.
9c. as never / as any on skill keys
The SDK is fully typed. If TS complains about 'ai.skills.generateBrandReview':
- Did you pass
modules: [AI]toClientSDK.init()? (Mode A) - Did you use
client.mutate(notclient.query)? AI skills are mutations. - Is the key spelled exactly as shown? (case-sensitive)
Do not cast — fix the underlying issue.
9d. Treating generateBrandReview as a query
It's a mutation in both modes (POST under the hood). In Mode A use client.mutate, not client.query. In Mode B it's just a method call, no mode distinction needed.
9d-bis. Flat {body, query} in Mode A (the TS2353 trap)
First-attempt bug observed in real use: writing client.mutate('ai.skills.generateBrandReview', { body: {...}, query: {...} }) — flat at the top level, like the Mode B shape — fails tsc --noEmit with TS2353: Object literal may only specify known properties, and 'body' does not exist in type 'MutationOptions<…>'. Mode A wraps hey-api options under params: ({ params: { body, query, headers?, path? } }), same as every xmc.* mutation. See § 3b for the canonical shape. Mode B (experimental client, § 4b) uses flat options — do NOT add the params: wrapper there.
9e. Unauthenticated file URLs from internal hosts
If url points to a host that requires auth, the server can't download it — include the auth field. Forgotten auth is a common cause of "file not found" errors even when the URL is reachable from a browser.
9f. Oversized base64 payloads — silent SyntaxError on submit
Base64-inline files in url inflate request size ~33%. There is an undocumented practical payload ceiling somewhere between ~30 KB (confirmed working) and ~5 MB (confirmed failing, with a 3.8 MB PDF → ~5 MB base64). When the ceiling is exceeded, the Marketplace bridge or AI backend returns an empty / truncated response body, and the SDK's JSON response handler surfaces the failure as:
SyntaxError: Unexpected end of JSON input
Failed to execute 'json' on 'Response': Unexpected end of JSON input
The error name mentions nothing about size — pure diagnostic trap. If you see this exact SyntaxError on a generateBrandReview call, payload size is the first thing to suspect.
Practical rule: keep base64 payloads under ~1 MB; anything above is risky. For larger files, host the file publicly (or behind auth via § 6d) and pass an HTTPS URL instead of an inline data URL. A reasonable UI guardrail: warn users at 1 MB base64 and hard-warn at 3 MB.
9g. detail tuning
'low'— cheap, fast, OK for small UI-style images'auto'(default) — balanced'high'— full LLM vision pass; use for hero imagery and detailed brand reviews
Pick explicitly once, don't oscillate per-request. Document the choice in the implementation plan.
10. Mode A vs Mode B — quick reference
// ─── Mode A — inside a Client SDK iframe app ──────────────────────────
import { ClientSDK } from '@sitecore-marketplace-sdk/client';
import { AI } from '@sitecore-marketplace-sdk/ai';
const client = await ClientSDK.init({ target: window.parent, modules: [AI] });
const result = await client.mutate('ai.skills.generateBrandReview', {
params: {
body: { brandkitId, input: { headline, body } },
query: { sitecoreContextId },
},
});
// ─── Mode B — server-to-server / standalone ───────────────────────────
import { experimental_createAIClient } from '@sitecore-marketplace-sdk/ai';
const ai = await experimental_createAIClient({
getAccessToken: async () => auth0.getAccessToken().then(r => r.token),
});
const brandReview = await ai.skills.generateBrandReview({
body: { brandkitId, input: { headline, body } },
query: { sitecoreContextId },
});
11. Agent guidance
During discovery / requirements: If the feature involves "brand compliance check", "AI-powered review", or "content scoring against a brand kit" — this SDK is the path. Surface in the requirements whether the content is text-only or also includes images/documents (affects input design).
During architecture: Pick mode (A vs B) in the ADR. Default to Mode A unless the app runs outside the iframe. Document the brand-kit selection strategy (single brandkitId vs user-selected) and whether sections targeting is used. Record the detail level decision for images.
During implementation planning: Specify (a) which mode, (b) exact key strings ('ai.skills.generateBrandReview'), (c) ExtractableFile usage and mime types if images/documents are involved, (d) for Mode B, the env vars and sitecoreContextId capture strategy. If Mode B, include a task for the one-time application.context capture page.
During testing: Test scenarios must cover (a) text-only input, (b) image input with each supported mimeType, (c) document input with and without auth, (d) large files / timeout behavior, (e) Mode B token expiry / refresh. Responses are LLM-dependent — verify in the real portal with a known brand kit.
During implementation: Use exact key strings. Call client.mutate (not query) in Mode A. For Mode B, never hardcode the access token — always go through getAccessToken. Unwrap Mode A responses with .data (per the marketplace-sdk-client skill, § 8b).
Sitecore Marketplace Client SDK
This skill is a catalog, not a contract. It documents
ClientSDK.initoptions and thequery/mutate/subscribeverb shapes. It does not document the response envelope of any specific module (xmc.*,ai.*) — those are determined by the module's generated types innode_modules. Before writingclient.query(...), open the relevant*.d.tsand cite the path inline. Mock fixtures must match the declared types.
When to use
- The project uses
@sitecore-marketplace-sdk/client(required for all Marketplace apps) - The PRD or architecture mentions Marketplace integration, SitecoreAI extension, or embedded app
- The scaffold decision (the
setup-scaffoldskill) chose Scaffold 2 (Client-Side) or Scaffold 3 (Full-Stack) - The project identifies extension points like Full Screen, Pages Context Panel, or Dashboard Blocks
For XMC endpoints (xmc.* keys, GraphQL, content-transfer) see the marketplace-sdk-xmc skill.
For AI skills module see the marketplace-sdk-ai skill.
For app lifecycle, auth model, architectures (including experimental server-to-server mode) see the marketplace-sdk-lifecycle skill.
For local dev loop, iframe auth debugging see the marketplace-sdk-testing-debug skill.
1. Package overview
| Package | Purpose |
|---|---|
@sitecore-marketplace-sdk/core | PostMessage bridge, handshake, event emitter (internal) |
@sitecore-marketplace-sdk/client | High-level query/mutate/subscribe API — this skill |
@sitecore-marketplace-sdk/xmc | XMC module — see the marketplace-sdk-xmc skill |
@sitecore-marketplace-sdk/ai | AI skills module — see the marketplace-sdk-ai skill |
The client package is what you import. The core package is an internal dependency. The xmc and ai modules plug into the client via the module system and extend its type maps.
Install (always latest): npm install @sitecore-marketplace-sdk/client@latest @sitecore-marketplace-sdk/xmc@latest @sitecore-marketplace-sdk/ai@latest — pick only the modules the app actually uses.
Scope of this file: client-side iframe integration (ClientSDK.init() + base query/mutate/subscribe). Module-specific keys live in their own files.
2. Initialization
import { ClientSDK } from '@sitecore-marketplace-sdk/client';
import { XMC } from '@sitecore-marketplace-sdk/xmc';
import { AI } from '@sitecore-marketplace-sdk/ai';
const client = await ClientSDK.init({
target: window.parent, // REQUIRED — the host window (always window.parent in iframe)
modules: [XMC, AI], // Register zero or more modules
origin?: string, // Host origin — auto-detected if omitted
timeout?: number, // Handshake timeout in ms (default: 30000)
});
Critical rules
target: window.parent— Marketplace apps always run in an iframe. The target is the host window.- Call
ClientSDK.init()only once. Both patterns below enforce this: the Provider viauseEffect+ state, the singleton via a module-level promise. - Client-side only. The SDK uses
postMessage— it cannot run during SSR. Always guard with'use client'and dynamic imports. client.destroy()— Call on unmount to clean up subscriptions and message listeners.
Provider pattern — scaffold default
The shadcn quickstart (the setup-marketplace-client-side skill) ships a React Context pattern in components/providers/marketplace.tsx — MarketplaceProvider wraps the app at app/layout.tsx, exposes client + applicationContext via context, renders children only after both resolve, and provides useMarketplaceClient() / useAppContext() hooks for consumers.
The full template (drop-in marketplace.tsx) lives at assets/marketplace-provider.tsx. Copy it verbatim if your scaffold doesn't already ship it; extend modules: [XMC] to [XMC, AI] when the app uses AI skills.
Singleton pattern — alternative for non-React consumers
Use a module-level singleton promise when the SDK is consumed outside the React tree (library exports, utility modules, top-level scripts). Same init contract as the Provider, different consumption shape — getSDKClient() returns the resolved client and ensures ClientSDK.init() runs only once. The dynamic-imports inside the singleton avoid the SSR crash that bites if you statically import @sitecore-marketplace-sdk/client in a server component.
Drop-in template at assets/sdk-client-singleton.ts.
Do not mix both patterns in the same app — that creates two parallel init paths and risks duplicate handshakes. Pick one based on whether the SDK is consumed primarily inside or outside React.
Alternative: experimental server-to-server mode
For apps running outside the iframe (standalone, cron jobs, microservices, server routes that need XMC/AI without portal brokering), both the XMC and AI packages offer experimental direct clients (experimental_createXMCClient, experimental_createAIClient). These bypass the postMessage bridge and call XMC/AI APIs directly with an Auth0 access token you supply.
Experimental — subject to breaking changes. Only use when the iframe Client SDK path can't satisfy the requirement. For the architecture decision and Auth0 config, see the marketplace-sdk-lifecycle skill, § 4c + § 5. For the per-package API: the marketplace-sdk-xmc skill, § 2b, and the marketplace-sdk-ai skill, § 4.
3. Core API patterns
The SDK exposes three verbs: query, mutate, subscribe. Each verb is fully typed via mapped types — the key string determines parameter and response types at compile time.
3a. query
const result = await client.query(key, options?);
// result: { data, error, status, isLoading, isError, isSuccess, refetch, unsubscribe? }
- Returns a result object, not raw data. Access
.datafor the payload. - Some queries support live subscriptions (see
subscribefield in QueryMap).
3b. mutate
const response = await client.mutate(key, options?);
// response is the direct return value (typed per MutationMap)
- Triggers state changes on the host.
- The options object shape varies per key — check the relevant module file (the
marketplace-sdk-xmcormarketplace-sdk-aiskills) for its MutationMap.
3c. subscribe
const unsubscribe = client.subscribe(eventKey, {
onData: (data) => { ... },
onError?: (error) => { ... },
});
// Call unsubscribe() to stop listening
- Event-based subscriptions for real-time updates.
- Always store and call the returned
unsubscribefunction on cleanup.
3d. Utility methods
client.logout(): Promise<void>
client.openProfile(): Promise<void>
client.navigateToExternalUrl(url: string, newTab?: boolean): Promise<void>
client.emitRouteEvent(route: string): Promise<void>
client.getValue(): Promise<any>
client.setValue(value: string, canvasReload?: boolean): Promise<void>
client.closeApp(): Promise<void>
client.destroy(): void
3e. getValue / setValue — the Custom Field read/write surface
getValue / setValue are the primary read/write surface for the xmc:pages:customfield extension point (§ 7 → references/extension-points.md). There is no dedicated QueryMap / MutationMap key for custom-field values — these utility methods are the contract.
Runtime shape. At runtime the value is a string — typically JSON, but the SDK contract is "opaque string". setValue enforces this (value: string). getValue currently returns Promise<any> (upstream type sloppiness; in the meantime treat the return as Promise<string> in your own code).
async function readFieldValue(client: ClientSDK): Promise<unknown> {
const raw = await client.getValue();
if (typeof raw !== "string") return raw;
try {
return JSON.parse(raw);
} catch {
return raw; // plain string — field wasn't JSON-shaped
}
}
async function writeFieldValue(
client: ClientSDK,
value: unknown,
canvasReload = true,
): Promise<void> {
const payload = typeof value === "string" ? value : JSON.stringify(value);
await client.setValue(payload, canvasReload);
}
canvasReload parameter. Passing true tells Pages to re-render the canvas after the write — use this when the field change should be visible in the preview immediately (most common). Pass false for background writes where the canvas shouldn't flicker.
Do NOT propagate any out of your read wrapper — narrow it to string / unknown at the boundary. Downstream code that types its field shape should parse into a Zod / io-ts schema or a hand-rolled type guard, not a cast.
4. Base QueryMap (built into client — no module needed)
| Key | Params | Response | Subscribable |
|---|---|---|---|
'host.user' | void | UserInfo { id, name, email } — at runtime the full Auth0 claim set (see § 8h) | no |
'host.state' | void | HostState | yes |
'host.route' | void | string | no |
'application.context' | void | ApplicationContext | no |
'site.context' | void | SiteContext | no |
'pages.context' | void | PagesContext | yes |
For the full ApplicationContext and PagesContext interface shapes, plus the canonical sitecoreContextId extraction pattern (with the cast-vs-guard discussion and the requireContextId() typed helper), see references/base-maps.md.
5. Base MutationMap (built into client)
| Key | Params | Response |
|---|---|---|
'pages.reloadCanvas' | void | void |
'pages.context' | { itemId?, language?, itemVersion? } | void |
Navigate to a page in Pages editor:
await client.mutate('pages.context', {
params: { itemId: 'GUID-HERE' },
});
6. Subscriptions — two distinct code paths
The SDK exposes two different mechanisms for receiving live updates. They are not interchangeable — picking the wrong one is a typecheck error.
| Path | Trigger | Used for | Returns |
|---|---|---|---|
| A. Subscribe-via-query | client.query(K, { subscribe: true, onSuccess }) | QueryMap keys with subscribable: yes (e.g. pages.context, host.state) | QueryResult with optional unsubscribe |
| B. Subscribe-verb | client.subscribe(K, { onData, onError? }) | SubscribeMap keys — event-only firehoses (e.g. pages.content.fieldsUpdated) | () => void teardown |
How to pick: look up the key. QueryMap (§ 4) with subscribable: yes → path A. SubscribeMap events → path B. A key never lives in both maps; the wrong call won't typecheck.
For full mechanics — both code patterns, the SubscribeMap event table, the client-side filter trap on pages.content.fieldsUpdated, and the rationale for two paths — see references/subscriptions.md.
7. Extension points
The per-extension-point table — which queries are available, iframe viewport constraints, what the host injects — is in references/extension-points.md. Open it when picking or wiring an extension point; getValue / setValue (§ 3) is the contract for xmc:pages:customfield.
8. Common pitfalls
8a. TypeScript — do NOT use as never or as any
The SDK is fully typed. If TypeScript complains about a query key, the cause is one of:
- The relevant module wasn't registered (
modules: [XMC]ormodules: [AI]missing from init) - The key string is wrong (case-sensitive — check the reference files)
- You're passing params in the wrong structure
Fix: import the module, pass it to init, and use exact key strings. The TypeScript compiler will validate params and response types automatically.
8b. Response unwrapping
Single vs double .data depends on the call family and on Mode A vs Mode B — the full matrix with worked examples is in references/response-unwrap-matrix.md. Never guess the depth; look it up.
8c. WebGL in iframes
SitecoreAI may set sandbox attributes on the iframe. Check application.context → permissions.iframe.sandbox to see what's allowed. If WebGL is blocked:
- The
<canvas>element will render butgetContext('webgl')orgetContext('webgl2')returnsnull - Detect this early and fall back to 2D rendering
- Do NOT plan a full 3D rendering path without a validation spike first
8d. SSR and the SDK
The SDK uses window.parent and postMessage — it cannot run server-side.
Rules:
- Mark all SDK-using files with
'use client' - Use
next/dynamicwith{ ssr: false }for components that call the SDK - Never import SDK modules in server components, API routes, or middleware
- The singleton init pattern (§ 2) handles this correctly with dynamic imports
8e. Subscription cleanup
Always clean up subscriptions:
useEffect(() => {
const unsub = client.subscribe('pages.content.layoutUpdated', {
onData: (data) => { ... },
});
return () => unsub();
}, [client]);
Failing to clean up causes memory leaks and orphaned event listeners in the PostMessage bridge.
8f. Error codes
The error-code table (code → meaning → what to do) is in references/error-codes.md. Check it when a call rejects; the codes are stable across SDK versions.
8g. Iframe auth silently fails on HTTP or wrong cookie config
Running over HTTP or with misconfigured session/transaction cookies makes iframe login fail with no clear error. See the marketplace-sdk-testing-debug skill, § 4 for the mandatory cookie block + symptom table, § 6 for the step-by-step debugging checklist. Do not reproduce the config here — it drifts.
8h. tenantName is ABSENT on resourceAccess[] for a full-screen app — read the host.user claim
ApplicationResourceContext.tenantName is declared optional (core/dist/shared-types.d.ts:77), and
for an xmc:fullscreen app the host really leaves it out. Measured 2026-09-12 (a full-screen app on a live
org): resourceAccess[0] = { resourceId, tenantId, tenantDisplayName: "<org> / <environment>", context: { live, preview } } — no tenantName. Anything that needs the SitecoreAI tenant name — the
Page Builder deep link https://pages.sitecorecloud.io/editor?organization=&tenantName=&sc_site=&sc_itemid=&sc_lang=
above all — therefore read undefined and rendered a dead control, with every gate green.
The value IS on host.user. The SDK types the response as UserInfo { id, name, email }, but at
runtime it is the Auth0 claim set: https://auth.sitecorecloud.io/claims/tenant_name (also
…/tenant_id, …/org_id, …/org_name, …/roles, sc_org_region, sub, email). Resolve in order,
and keep the source:
const TENANT_NAME_CLAIM = "https://auth.sitecorecloud.io/claims/tenant_name";
const fromAccess = appCtx.resourceAccess?.find((r) => r.tenantName)?.tenantName;
const user = (await client.query("host.user")).data as Record<string, unknown>;
const tenantName = fromAccess ?? (user?.[TENANT_NAME_CLAIM] as string | undefined) ?? null;
Two consequences. (1) Do not build a half-address — a link with an empty tenantName opens Page
Builder on nothing, which reads as the app being broken; return null and say which part is missing.
(2) pages.context (the mutation) does not navigate from a full-screen app; the deep link in a
new tab is the working shape.
9. Testing — typed Vitest stubs for the SDK surface
Unit-testing harness code that calls client.query / mutate / subscribe / destroy requires a stubbed ClientSDK. The SDK's call signatures are overloaded and generic, so naked vi.fn() will fail tsc --noEmit with TS2348: Value of type 'Mock<Procedure | Constructable>' is not callable. — always pass the call signature as a generic: vi.fn<ClientSDK['query']>().
For the full pattern — typed stubs per verb, default return values, call-shape assertions for query/mutate, and subscribe-lifecycle assertions — see references/vitest-stubs.md.
10. Agent guidance
During architecture: When the architecture involves the Marketplace Client SDK, document the extension-point choice (§ 7 → references/extension-points.md) and whether modules (XMC, AI) are needed in the init. Record the handshake constraint (iframe-only) as an ADR if the app scope includes anything non-iframe.
During implementation planning: Specify (a) the singleton init pattern (§ 2), (b) which modules to register, (c) which extension points the app targets. All dev and validation runs against a registered test app in Cloud Portal — there is no mock-client path. For module-specific keys and params, defer to the marketplace-sdk-xmc or marketplace-sdk-ai skills.
During testing: Verify test scenarios for SDK error states (§ 8f: timeout, not connected, token error, handshake failed). Add a validation spike for iframe constraints if the app uses canvas/WebGL (§ 8c).
During implementation: Use the exact key strings documented here and in the module-specific files. Do not cast as never or as any — if TypeScript errors on a key, check that the right module is in modules: [...]. Unwrap results with .data. Always clean up subscriptions.
Sitecore Marketplace Extension-Point Routes
When to use
- Immediately after
setup-marketplace-client-sideorsetup-marketplace-full-stacksucceeds — the scaffold ships a singleapp/page.tsx; this skill turns it into the N routes the Cloud Portal will bind to. - Before (or alongside) Cloud Portal registration in the
marketplace-sdk-lifecycleskill, § 3 — the route values you pick here are what get pasted into App Studio → Extension points → Route URL. - When the user adds a new extension point to an existing app (e.g. "also expose this as a dashboard widget") — re-run the skill for the new point only.
For extension-point capabilities per point (queries available, iframe constraints), see the marketplace-sdk-client skill, § 7.
For Cloud Portal registration flow (what form fields exist), see the marketplace-sdk-lifecycle skill, § 3.
1. Extension-point reference
The Cloud Portal Extension points form exposes five options. Each maps to an SDK enum value (marketplace-sdk-client skill, § 7) and a fallback Route URL that the portal suggests if you don't override it.
| # | Display label (portal) | Area | SDK enum | Fallback Route URL | Multiple paths? |
|---|---|---|---|---|---|
| 1 | Standalone — Full screen in Cloud Portal | Cloud Portal shell (umbrella — sees all installs across the org) | standalone | /portal | No — single route |
| 2 | Full screen | SitecoreAI | xmc:fullscreen | /full-screen | No — single route |
| 3 | Dashboard widgets | SitecoreAI | xmc:dashboardblocks | /sitecoreai-dashboardwidget | Yes — one route per widget |
| 4 | Page context panel — left-hand panel | Page builder / SitecoreAI | xmc:pages:contextpanel | /pages-context | No — single route |
| 5 | Custom field — right-hand panel or context panel | Page builder / SitecoreAI | xmc:pages:customfield | /sitecoreai-customfield | No — single route |
Fallbacks are examples the portal ships — override them to match your app's naming convention. For multi-brand apps (SitecoreAI-specific vs generic), pick prefixes that make ownership obvious.
2. Prompt flow (what the agent asks)
Run this verbatim after scaffold success. Do not assume — always ask.
Prompt 1 — select extension points (multi-select)
Which Cloud Portal extension points will this app support? (pick one or more)
[ ] 1. Standalone — Full screen in Cloud Portal
[ ] 2. Full screen — SitecoreAI
[ ] 3. Dashboard widgets — SitecoreAI (supports multiple routes)
[ ] 4. Page context panel — Page builder / SitecoreAI
[ ] 5. Custom field — Page builder / SitecoreAI
Prompt 2 — route URL per selected point
For each selected point (one prompt per point):
Route URL for <display label>? [fallback: <fallback from § 1>]
Rules:
- Must start with
/. - Lowercase + kebab-case (matches portal convention).
- No trailing slash.
- Must be unique across the app's routes.
Prompt 3 — Dashboard widgets multi-path (only if # 3 selected)
Dashboard widgets can expose multiple widget routes (one per widget tile).
How many widget routes? [default: 1]
Then for each: repeat Prompt 2 with a widget-specific label, e.g. "Route URL for Dashboard widget 1? [fallback: /sitecoreai-dashboardwidget]". When count > 1, the fallback for widgets 2..N should be derived (e.g. /sitecoreai-dashboardwidget-2, -3, …) and confirmed.
Prompt 4 — landing route
The scaffold's app/page.tsx (root /) is the demo page. Ask:
How should the root route "/" behave?
(a) Keep the scaffold demo (application-context + listLanguages)
(b) Redirect to one of the extension-point routes (specify which)
(c) Return 404 / empty — not part of the app's surface
2e. Invalid input handling
If the user enters anything outside the documented set for any of Prompts 1–4, re-prompt with the same options — do not silently convert or assume a default. Examples:
- Prompt 1 with
"six"or"8"— out-of-range number. Re-prompt the full multi-select list. - Prompt 2 with
"portal"(no leading/) or"/Portal"(uppercase) — violates § 2 Route URL rules. Re-prompt with the fallback and the specific rule that failed ("must start with/" / "must be lowercase"). - Prompt 3 with
"0"or a negative number — re-prompt with the default hint. - Prompt 4 with
"d","yes", or anything outsidea/b/c— re-prompt showing only the three valid letters plus a one-line reminder of each option.
When re-prompting, echo back what the user entered and name the rule that rejected it. Never guess what they meant ("you said d, I'll assume a") — that hides the miscommunication and bakes in the wrong answer.
2f. Changing a selection mid-flow
If the user changes their mind after a prompt has been answered (e.g. "actually, make that Page context panel instead" after selecting Standalone), restart the affected prompts from the changed point, not the whole skill:
- Change in Prompt 1 (extension-point set) → re-run Prompts 2 + 3 from scratch; Prompt 4 answer is preserved only if it still references a valid new route.
- Change in Prompt 2 (route URL) → re-run that single prompt; Prompt 4 is re-asked only if it referenced the changed route.
- Change in Prompt 3 (widget count) → re-run Prompts 2 only for the affected widget indices.
- Change in Prompt 4 (root behavior) → re-run that single prompt.
Clear any partial file generation before restarting — if you already wrote app/<old-route>/page.tsx, delete it before the new prompt cycle so the route table stays consistent with the final answer. State what was deleted and why.
Hard rule: never carry forward a partial earlier answer that the restart invalidates. Example — if Prompt 2 named a route /portal and the user later drops Standalone from Prompt 1, the /portal answer is dead; do not reuse it for a different extension point.
3. Generating Next.js App Router files
For each (extension point, route) pair — including every Dashboard widget route — create:
app/<route-without-leading-slash>/page.tsx
Examples:
- Route
/portal→app/portal/page.tsx - Route
/full-screen→app/full-screen/page.tsx - Route
/pages-context→app/pages-context/page.tsx - Dashboard widget routes
/widgets/traffic+/widgets/performance→app/widgets/traffic/page.tsx+app/widgets/performance/page.tsx
Pick the template variant that matches the page's job:
| Variant | When | Key imports |
|---|---|---|
| § 3a Full hooks | Page calls SDK queries/mutations (typical default) | useMarketplaceClient, useAppContext |
| § 3b Reads-only | Page only displays appContext — no SDK calls | useAppContext only |
| § 3c Redirect | Prompt 4 option (b) — root / redirects to an extension-point route | redirect from next/navigation |
| § 3d 404 | Prompt 4 option (c) — root / returns 404 | notFound from next/navigation |
3a. Full hooks template (default)
Use when the page actually calls the SDK. The scaffold's MarketplaceProvider hooks (from setup-marketplace-client-side or setup-marketplace-full-stack) provide both client and context.
"use client";
import { useAppContext, useMarketplaceClient } from "@/components/providers/marketplace";
export default function <ExtensionPointName>Page() {
const client = useMarketplaceClient();
const appContext = useAppContext();
// Extension-point-specific UI goes here.
// See the marketplace-sdk-client skill, § 7, for which queries / subscriptions this extension point supports.
// For sitecoreContextId extraction, see the marketplace-sdk-xmc skill, § 6a — guard before use, do not cast.
return <div>{/* ... */}</div>;
}
3b. Reads-only variant
Use when the page only reads appContext — for example, a Page context panel that shows the selected page's metadata without issuing XMC calls. Importing useMarketplaceClient here would be unused and trip @typescript-eslint/no-unused-vars.
"use client";
import { useAppContext } from "@/components/providers/marketplace";
export default function <ExtensionPointName>Page() {
const appContext = useAppContext();
return (
<div className="p-4">
<h1 className="text-lg font-semibold">{appContext.name ?? "App"}</h1>
<pre className="bg-muted p-2 rounded text-xs overflow-auto">
{JSON.stringify(appContext, null, 2)}
</pre>
</div>
);
}
Promote to § 3a the moment the page needs to call client.query(...).
3c. Redirect template (Prompt 4 option b)
Use only for the root app/page.tsx when Prompt 4 answer was (b). Keeps / out of the extension-point surface by redirecting into the real route.
import { redirect } from "next/navigation";
export default function RootPage() {
redirect("/<target-route>"); // e.g. "/pages-context"
}
No "use client" directive — redirect() runs at render time on the server. No hooks, no provider access.
3d. 404 template (Prompt 4 option c)
Use only for the root app/page.tsx when Prompt 4 answer was (c). Returns Next.js's not-found page for requests to /, making it clear the app has no landing surface.
import { notFound } from "next/navigation";
export default function RootPage() {
notFound();
}
Same server-side rules as § 3c — no "use client", no hooks.
Per-extension-point guidance for what goes inside:
| Extension point | Typical content | Supported queries |
|---|---|---|
| Standalone | Full portal-area UI — dashboards, tool landings, multi-environment admin UIs | All base + XMC (no pages.context). Umbrella surface — application.context.resourceAccess[] lists every installation of the app across the organisation (one per SitecoreAI install, each with its own live + preview sitecoreContextId). XMC calls scope via the chosen install's contextId, so one Standalone app can drive many environments. Worked pattern: the marketplace-sdk-xmc skill, § 2c. |
| Full screen | Full-pane SitecoreAI tool | All base + XMC (no pages.context) |
| Dashboard widget | Compact widget — single-metric, chart, quick action | Limited to dashboard scope; each widget route is independent |
| Page context panel | Left-hand panel beside the Pages canvas — reads selected page | Base + XMC + subscribable pages.context (via the marketplace-sdk-client skill, § 6a) |
| Custom field | Right-hand / in-canvas field editor — reads + writes a single field | pages.context + getValue / setValue (read/write surface — see the marketplace-sdk-client skill, § 3d + § 3e). Field-change events via client.subscribe('pages.content.fieldsUpdated', …) (see the marketplace-sdk-client skill, § 6b); filter by fieldId / itemId client-side. |
Do not copy-paste Dashboard widget code between widget routes — each one is its own logical surface. Share logic via hooks, not via duplicated files.
4. Cloud Portal registration output
After Prompt 2–3 are answered, emit this table for the user to paste into Cloud Portal → App Studio → your app → Extension points:
Extension point | Route URL
-------------------------|---------------------------------
Standalone | <user-chosen or fallback>
Full screen | <user-chosen or fallback>
Dashboard widgets #1 | <user-chosen or fallback>
Dashboard widgets #2 | <user-chosen or fallback>
...
Page context panel | <user-chosen or fallback>
Custom field | <user-chosen or fallback>
Only emit rows for extension points the user selected in Prompt 1. Each Dashboard widget row becomes a separate extension-point entry in the portal.
5. Common pitfalls
5a. Running this before scaffold
The templated page.tsx files import @/components/providers/marketplace — that module only exists after Scaffold 2/3. Run this skill after the scaffold, not before.
5b. Forgetting to update Cloud Portal
Creating the Next.js routes is only half the job. The portal binds extension points by Route URL — if you change a route later, update App Studio too or the iframe will load the old URL and break the handshake (see the marketplace-sdk-testing-debug skill, § 6c).
5c. Using the root / route for an extension point
The scaffold's app/page.tsx is a demo. If you bind an extension point to /, that demo becomes production. Prompt 4 exists to force the decision — don't skip it.
5c-bis. Root / template fires inside <MarketplaceProvider> — § 3c and § 3d never resolve outside the portal iframe
The scaffold wraps <MarketplaceProvider> at app/layout.tsx, which means every route — including the root / — renders as a child of that provider. The provider's state machine renders <div>Attempting to connect to Sitecore Marketplace...</div> until ClientSDK.init() resolves against a parent window. Outside the portal iframe (i.e. visiting http://localhost:3000/ directly in a browser), that init never resolves — the provider sits on the loader forever and the § 3c redirect() / § 3d notFound() page never renders.
Inside the portal iframe this is a non-issue: widgets and extension points are loaded by their own route URLs, never /. The trap bites only during local smoke tests.
Two ways to handle it:
- (a) Accept the trap. Document for your team that local smoke tests must hit a widget / extension-point route directly (
http://localhost:3000/<your-extension-route>), never/. This is the default for most harnesses — simplest, zero refactor. - (b) Move
<MarketplaceProvider>out of the root layout. Introduce a per-extension-point layout (e.g.app/(marketplace)/layout.tsxorapp/dashboard/layout.tsx) that wraps only the extension-point routes. The root/then renders provider-free and the redirect / 404 templates work exactly as documented. More refactor, cleaner long-term story.
Pick one explicitly during architecture so the implementing developer knows which pattern to use. Do not leave the root route and provider-wrap decision implicit — it surfaces as a "why does my redirect hang?" bug every time.
5d. Dashboard widgets as a single route
Dashboard widgets are the only extension point that supports multiple routes. Binding all widgets to one route means one React component has to switch based on some context param — the portal doesn't pass a "which widget" identifier cleanly. One route per widget is cleaner.
5e. Naming that fights the portal
The fallback /sitecoreai-* names make sense inside SitecoreAI but look out of place in a generic custom app. Pick names that match the app's brand — but keep them lowercase + kebab-case so the portal UI doesn't reject them.
5f. Case sensitivity
Route URLs are case-sensitive in the portal and in Next.js. /Full-Screen and /full-screen are different routes. Stay lowercase.
6. Agent guidance
During architecture: Before finalizing the ADR, list which extension points the app will target and record the route URLs in the architecture doc. The ADR drives the Cloud Portal registration values; if it's blank here, the implementing developer has to guess.
During implementation planning: the plan's stack/tooling section must include: (a) the list of extension points from this skill's Prompt 1, (b) the route URLs from Prompt 2–3, (c) a discrete task per app/<route>/page.tsx file to create, (d) Prompt 4's answer for the root / route. The Cloud Portal registration table (§ 4) is an output artifact the user will need.
During testing: Every route URL registered in the portal must also resolve in the running app (and vice versa — no orphan routes). Test scenarios: (a) navigate to each registered route and verify the page loads, (b) verify the portal binding actually opens the correct page, (c) for Dashboard widgets, verify each widget route renders the right widget.
During implementation: Do not invent route URLs — use the ones in the implementation plan exactly. When adding a new extension point later, re-run this skill (Prompts 1–4) rather than hand-rolling a route.
Marketplace App — Host-Frame Visual Testing
When to use
- A test phase runs and the project is a Marketplace app.
- You need a screenshot of "just the app" extracted from the surrounding Sitecore portal chrome.
- You need to verify the implementation under realistic host conditions (real iframe sandbox, real Blok tokens applied by host, real viewport size). If a POC clickdummy exists for the design, this skill also covers comparing the host-frame render to that POC as a visual ground truth (§ 6 — skip if you don't have a POC).
A standalone localhost:3000 hit is not an acceptable substitute. Marketplace apps depend on XMC.host, XMC.context, theme, locale, and auth coming from the parent frame — they render blank or in error state outside of the host.
1. The contract — what the user supplies, what the agent does
User supplies (mandatory inputs before this skill can run)
| Input | Example | Purpose |
|---|---|---|
| Host URL | https://xmcloud.sitecore.com/.../pages?context=... | The deep link into the Sitecore surface that embeds the app. |
| App origin | https://localhost:3000 (dev) or the registered Marketplace app URL | Used as the iframe locator pattern (iframe[src*="<origin>"]). |
| Auth confirmation | "I'm logged in" / "I'll log in when the browser opens" | Agent stays interactive; never tries to script SSO. |
If any of the three is missing, ask for it and stop — do not proceed with a fake or guessed host URL.
Agent does
- Opens host URL in Playwright MCP browser.
- Pauses for interactive SSO if the user says they need to log in.
- Locates the app's iframe by origin match.
- Captures a clipped screenshot of just the iframe's bounding box.
- Drives the app through PRD acceptance states; clip-screenshots each.
- If a POC clickdummy exists, compares each clipped screenshot against it as the visual ground truth (§ 6). Otherwise records the clipped states as the run's evidence baseline.
- Records findings in the test report with side-by-side embedded images (POC comparison) or single-image tables (no POC).
2. Auth handling — interactive only
Do not attempt to script Sitecore SSO. Do not try to inject cookies, tokens, or storage state. The agent's contract:
- Open the host URL with Playwright MCP.
- Output to the user: "The browser is open at the host URL. Log in if prompted, then reply READY."
- Stop and wait for
READY(or equivalent confirmation) before continuing. - After
READY, run a probe —browser_snapshot— and verify the page is not the Sitecore login screen by checking for the host's authenticated chrome (e.g., portal navigation, app launcher). If it still looks like a login page, ask the user to confirm again.
No persisted storage state. Each test run starts a fresh browser session and goes through interactive login. This is by explicit preference — do not introduce a "remember me" optimization without asking.
3. Locating the iframe
Marketplace apps are always iframed by their extension point. The locator pattern is:
iframe[src*="<app-origin>"]
Step-by-step (Playwright MCP)
Use Playwright's locator API — never reach into iframe DOM via raw JS evaluation against an unknown origin.
- Use
browser_snapshotto get an accessibility tree of the host page; verify the iframe is visible. - Use a locator like
page.locator('iframe').filter({ has: ... })or directly inspect frames viapage.frames(). Each frame exposes.url(); pick the one whose URL contains the app origin. - If no frame matches, the app is not currently mounted into this host context.
Common locator failures and how to recover:
| Symptom | Likely cause | Recovery |
|---|---|---|
| Zero iframes match | App not loaded into this host context yet | Ask user to navigate to the page/panel where the app appears, then retry |
| Multiple iframes match same origin | App is a Page extension AND a ContextPanel extension and both mounted | Pick by extension-point hint in the URL query (e.g. ?placement=context-panel) — ask the user which one to test |
Iframe src is blank or about:blank | Lazy mount; iframe exists but app hasn't booted | browser_wait_for until the src becomes the app origin (timeout 30s) |
Iframe is chrome-error://chromewebdata/ | Self-signed cert rejected (see the marketplace-sdk-testing-debug skill's references/https-traps.md § 2) | Stop and tell the user — this is a local-cert problem, not a test failure |
4. Clipping the screenshot to just the app
Once the iframe is located, get its bounding box in the parent page's coordinate space and pass it as the clip rectangle to browser_take_screenshot.
// Use a Playwright locator (not raw page.evaluate) so this works cross-origin.
// boundingBox() returns the iframe's position in the top-level document — exactly
// what we need for screenshot clipping, regardless of the iframe's content origin.
const iframeLocator = page.locator(`iframe[src*="${APP_ORIGIN}"]`).first();
const box = await iframeLocator.boundingBox();
if (!box || box.width === 0 || box.height === 0) {
// App iframe is mounted but invisible (display:none / collapsed) or not present.
// See § 8b for triage.
throw new Error('App iframe has no visible bounding box');
}
await page.screenshot({
path: 'test-evidence/state-<name>.png',
clip: {
x: Math.round(box.x),
y: Math.round(box.y),
width: Math.round(box.width),
height: Math.round(box.height),
},
});
Why this works: screenshot clipping operates on the parent page's pixels — it does not require entering the iframe's content document, so it works equally well for same-origin and cross-origin iframes. This is the core reason this approach holds up even when the app is at localhost:3000 and the host is xmcloud.sitecore.com.
Evidence file naming: test-evidence/<state-name>-<timestamp>.png under the product folder. Embed in the test report via relative markdown image links.
5. Driving the app through states
Once you've captured the empty / loaded state, drive the app through PRD acceptance criteria.
Cross-origin iframe (normal Marketplace case)
Raw JS evaluation cannot reach into the frame's DOM, but Playwright does support cross-origin frame interaction via locators. Use page.frameLocator('iframe[src*="<origin>"]'):
const appFrame = page.frameLocator(`iframe[src*="${APP_ORIGIN}"]`);
await appFrame.getByRole('button', { name: 'Copy Live URL' }).click();
await appFrame.getByRole('status').waitFor({ state: 'visible' });
// ... then re-clip the iframe (§ 4) to capture the new visual state
What does NOT work cross-origin:
- Raw script execution against the frame's
documentfrom the parent - Reading the frame's
documentfrom the parent context - Direct DOM querying via parent-context script reaching into
iframe.contentDocument
What DOES work:
- Locator-based interaction (
getByRole,getByText,getByTestId,locator(selector)) - Clicks, fills, hovers, keyboard input via locators
- Waiting for visibility / attached / detached states via locators
- Screenshot clipping (operates on parent pixels — origin doesn't matter)
For state coverage that genuinely requires DOM read access (e.g., "verify computed background color of element X"), fall back to visual diff against the POC instead — that is the canonical truth path for this skill.
6. Visual comparison — POC clickdummy as ground truth (optional)
This section applies only if your project produced a POC clickdummy during design (typically at pocs/poc-vN/index.html under the project root). If your workflow does not use POC clickdummies, skip this section — the clipped iframe screenshots from § 4–5 are themselves the run's evidence; record them in the test report and judge against the PRD's acceptance criteria directly.
The winning POC clickdummy is the visual baseline for first-run testing when it exists. The five-axis comparison below grounds visual judgment in something explicit instead of leaving "looks right" to memory.
Comparison protocol
-
Open the POC in a second Playwright tab at the same viewport size as the iframe's bounding box (so the POC's rendered width matches the host-frame clip width).
-
Take a screenshot of the POC at the same logical state (e.g., "default", "after copy", "error state"). The POC must support these states — that's why architecture mandates state coverage.
-
Place the two images side-by-side in the test report (
| Host clip | POC reference |table row per state). -
Compare on five axes, scoring PASS / WARN / FAIL with a one-line note each:
- Layout & spacing — proportions, gutters, alignment grid
- Typography — family, weight, size scale, leading
- Color & contrast — semantic Blok tokens applied correctly (the host applies real Blok theme; the POC pulls Blok theme CSS or copied tokens — they should match)
- Component anatomy — Buttons, Cards, Sidebars use real
@blok/*shapes (no fabricated approximations) - State fidelity — hover, focus, active, error, empty, loading match the POC's documented states
- Long-list relationship visibility — when the surface contains paired or related lists (rendering rows + datasource rows, files + owners, items + assignees), zoom out / paste a 20+-item fixture and confirm cross-row hover affinity, color-tag matching, and cross-list visual link still work. Small-tenant fidelity won't catch this. If the design relies on the lists being visually connected, this axis is mandatory, not optional.
-
Threshold for FAIL: any axis where the host clip and the POC diverge in a way that a Sitecore user would perceive as "not Blok" or "not the agreed design." Subjective judgment is fine — the QA reviewer names what they see.
After first run
The POC stays as ground truth across subsequent runs unless the design is intentionally changed. If the user asks for a design change post-implementation:
- Re-run the architecture/POC step to update the POC, OR
- Update the POC clickdummy directly and note the refresh in your project's design log so it isn't mistaken for drift on the next run.
Do not silently promote a host-frame screenshot to "new baseline" without an explicit POC update — that defeats the design-discipline purpose of the POC.
7. Output — test-evidence section in the test report
Embed in your project's test report (e.g. <project>/plans/test-report-<timestamp>.md, or wherever your workflow tracks test evidence):
## Visual Testing — Host-Frame (Marketplace)
**Host URL:** `<URL the user supplied>`
**App origin:** `<origin>`
**POC reference:** `pocs/poc-vN/index.html` (winning variant)
**Auth:** interactive (user logged in at <time>)
**Browser viewport:** <width>x<height>
**Iframe clip box:** x=<x> y=<y> w=<w> h=<h>
### State coverage
| State | Host clip | POC reference | Layout | Typography | Color | Anatomy | State | Verdict |
|-------|-----------|---------------|--------|------------|-------|---------|-------|---------|
| Default |  |  | PASS | PASS | PASS | PASS | PASS | PASS |
| After copy |  |  | PASS | PASS | WARN — chip color slightly off | PASS | PASS | WARN |
| Error |  |  | PASS | PASS | PASS | PASS | FAIL — error ring not red | FAIL |
### Findings carried into the report
- (one row per FAIL or WARN, with severity and a proposed fix)
8. Pitfalls
8a. Host URL points to a context where the app isn't installed
The user gives a URL into a Sitecore surface that doesn't yet have the test app registered → no iframe matches the origin. Symptom is identical to "app crashed." Always check the marketplace-sdk-testing-debug skill, § 2, first — is the test app actually installed in this environment?
8b. Iframe is mounted but invisible (display:none / collapsed)
Bounding box has zero width or height. Clip rectangle would be invalid. Check width > 0 && height > 0 before screenshotting; if zero, the app's extension point is registered but not currently displayed — ask the user to navigate to the surface where it appears.
8c. POC at different viewport from host clip
The host iframe might be 320x600 (Context Panel) while the POC was authored at desktop 1280x800. Open the POC at the iframe's clip dimensions when comparing — otherwise spacing and breakpoints will diverge for cosmetic reasons unrelated to implementation quality.
8d. Theme drift — host applies dark mode, POC was authored light
Read the host's applied theme (visible in the host's portal chrome) and toggle the POC to match before comparison. Both POC and host should expose a theme toggle (per architecture's Blok requirements).
8e. Sandbox-restricted features
Some Marketplace iframe features (downloads, popups, clipboard) are subject to the iframe sandbox attribute (see the marketplace-sdk-testing-debug skill, § 7a). If a state can't be reached because the sandbox blocks it, that's an environmental finding — record it as a sandbox observation, not as a failed test.
9. Agent guidance
When testing a Marketplace app: the canonical visual test target is the clipped iframe inside the host, not a standalone localhost render. Standalone-render testing is acceptable only as a smoke-level sanity check (does the app boot at all?) — it never substitutes for host-frame testing. The winning POC clickdummy is the first-run ground truth; do not promote host-frame screenshots to baselines silently.
When fixing host-frame findings: re-run the same host-frame check (not a localhost re-render) to verify the fix. The user does not need to re-supply the host URL within a single test session — reuse it.
When orchestrating visual testing: before starting, ask the user for the host URL and app origin if the project is a Marketplace app. Do not proceed with visual testing if either is missing. Auth is always interactive — do not persist storage state.
Sitecore Marketplace App Lifecycle
This skill is a catalog, not a contract. It documents lifecycle phases, app-architecture options, and Auth0 model. It does not document tenant-side preconditions (e.g.
Sites.Host.targetHostnamemust be populated for the Live URL to resolve), nor does it document the runtime availability of any specific SDK call. Verify in a real tenant before declaring shipped.
When to use
- A project is starting a new Marketplace integration and you need to decide custom vs public
- The architecture phase needs to pick an app architecture (client-side iframe, full-stack, standalone with server-to-server)
- You need to know what fields/values to register in Cloud Portal → App Studio
- You are configuring Auth0 for iframe compatibility (cookies, scopes, orgId/tenantId)
- You are preparing a public app for submission and need the Sitecore/Blok checklist
For Client SDK reference (ClientSDK.init, query/mutate/subscribe, extension-point types) see the marketplace-sdk-client skill.
For XMC endpoint keys (xmc.* — sites, pages, agent, GraphQL) see the marketplace-sdk-xmc skill.
For AI skills module (@sitecore-marketplace-sdk/ai) see the marketplace-sdk-ai skill.
For local dev + iframe debugging see the marketplace-sdk-testing-debug skill.
1. Custom vs public apps
| Dimension | Custom app | Public app |
|---|---|---|
| Availability | Your organization + any organizations you whitelist | All Sitecore organizations via public Marketplace listing |
| Approval | None — self-serve | Sitecore review required before publication |
| Hosting | Self-hosted (your infra / cloud) | Self-hosted, but discoverable via public Marketplace |
| Listing | Private — not in public Marketplace | Public Marketplace listing (https://portal.sitecorecloud.io/marketplace) |
| Blok compliance | Recommended | Effectively required for submission approval |
| Typical use | Internal tools, customer-specific integrations, prototypes | Reusable integrations distributed to the ecosystem |
Decision rule: If the integration is for a single customer or internal use, build a custom app. Only target public if the integration is reusable across organizations and you accept the review/compliance overhead.
2. Lifecycle phases
2a. Custom app — 5 phases
1. Register → Create the app in Cloud Portal → App Studio
2. Configure → Set extension points, API access, dev URL, authorization
3. Install → Install into one or more organizations
4. Build → Implement with Marketplace SDK (client / xmc / ai)
5. Finish → Post-build configuration (prod URL, access grants, updates)
Build (phase 4) and Install (phase 3) can be iterative — install early with a localhost dev URL, then iterate on code.
2b. Public app — 9 phases
1. Register → Same as custom
2. Configure → Same as custom
3. Install → Internal install for testing
4. Build → Implement with Marketplace SDK
5. Finish → Post-build configuration
6. Test → End-to-end verification in real portal
7. Prepare → Marketing materials, icons, descriptions, Blok review
8. Submit → Submit for Sitecore approval
9. Publish → Appears in public Marketplace after approval
Phases 7–9 are unique to public apps. Phases 1–6 are shared with custom apps.
3. What you register in Cloud Portal → App Studio
Required role: You must be Organization Admin or Organization Owner in the target Sitecore Cloud Portal organization.
What's configured during Register + Configure phases:
| Field / concept | Notes |
|---|---|
| App name | Distinct, descriptive. Use Test application suffix for throwaway test apps. |
| App URL (development) | https://localhost:3000 for local dev (must be HTTPS — see § 5). |
| App URL (production) | Set during Finish phase once hosting is live. |
| Extension points | One or more of standalone, xmc:fullscreen, xmc:pages:contextpanel, xmc:pages:customfield, xmc:dashboardblocks. See the marketplace-sdk-client skill, § 7, for capabilities per point. For Route URL per extension point (including multi-route Dashboard widgets) run the marketplace-sdk-extension-routes skill after scaffold. |
| API access | Which XMC/Authoring/Preview/Live/AI APIs the app may call. Enable only what's needed; for local dev enable all. |
| Authorization type | Determines whether Auth0 flow is iframe-embedded vs server-to-server (see § 5). |
| Environment binding | Which SitecoreAI environment(s) the app is installed against. |
| Access grants | Which users / groups in the organization may see the app (leave minimal during dev). |
Sub-pages that document each phase:
register-a-custom-app.html— app name, URL, extension pointsconfigure-and-activate-a-custom-app.html— API access, authorization, environmentsinstall-an-activated-custom-app.html— install into orgfinish-configuration.html— prod URL, access grantsupdate-an-installed-app.html— version updates
4. App architectures
Three architectures are viable. Pick one at architecture time — do not plan "we'll try both as fallbacks".
4a. Client-side iframe (most common)
Browser
└─ Sitecore portal (parent window)
└─ <iframe src="https://your-app.example.com">
└─ Your Next.js app
└─ ClientSDK.init({ target: window.parent, modules: [XMC, AI?] })
└─ client.query('xmc.sites.listSites', …)
- App communicates with XMC/AI only via the postMessage bridge to the portal.
- No direct XMC/AI API calls from the app — the portal brokers them.
- Auth is handled entirely by the portal; the app has no tokens of its own.
- Scaffold: the
setup-marketplace-client-sideskill, orsetup-marketplace-full-stackif you want SSR routes for your own UI only. - SDK reference: the
marketplace-sdk-clientskill for Client SDK base, themarketplace-sdk-xmcskill for XMC endpoints, themarketplace-sdk-aiskill for AI skills — all assume this architecture.
4b. Full-stack (iframe + own server routes)
Same as 4a, but the Next.js app has its own API routes for non-XMC server logic (your own DB, third-party APIs). XMC/AI calls still go through the Client SDK via postMessage.
- Use when the app has its own backend concerns (webhooks, scheduled jobs, your own data layer).
- Does not bypass the portal for XMC/AI calls.
- Scaffold: the
setup-marketplace-full-stackskill.
4c. Standalone + experimental server-to-server (direct XMC/AI)
Browser ←→ Your Next.js app ←→ Auth0 ←→ Sitecore XMC/AI APIs (direct)
(iframe or standalone)
- Uses
experimental_createXMCClientand/orexperimental_createAIClientwith an Auth0 access token. - Calls go directly to XMC/AI APIs from your server, not through the portal postMessage bridge.
- Required for scenarios where the app runs outside the iframe (background jobs, microservices, CLI) or when you need the full XMC/AI API surface without portal brokering.
- Status: experimental. Subject to breaking changes. Only use when the iframe path is insufficient.
- You still register the app in Cloud Portal with a
standaloneextension point.
When to use 4c:
- Background jobs / cron / webhooks that need XMC access
- AI skills that process content out-of-band from user interaction
- Server-side rendering where the client bundle can't hold an iframe SDK
When NOT to use 4c:
- The app runs inside the portal iframe and needs live page context (use 4a/4b)
- You just want to avoid learning the Client SDK (use 4a — it's the supported path)
4d. Hybrid: postMessage subscribe + client-credentials proxy
Browser
└─ Sitecore portal (parent window)
└─ <iframe src="https://your-app.example.com">
└─ Your Next.js app
├─ Client side: ClientSDK.init() — subscribes to pages.context, application.context
│ (Mode A — same as 4a/4b)
└─ Server side: app/api/<route>/route.ts
└─ uses OAuth 2.0 client-credentials (machine-to-machine)
to call SitecoreAI Agent / Pages / Publishing / Sites APIs
on behalf of an automation client
A hybrid that doesn't fit 4a/4b/4c cleanly. The app runs in the portal iframe (so the user sees pageId, siteName from pages.context) and has Next.js API routes that call SitecoreAI APIs server-to-server using OAuth 2.0 client-credentials — not Auth0 PKCE. The two halves talk to two different auth systems:
- Client (Mode A): postMessage to portal → iframe-brokered XMC calls. No tokens in browser.
- Server (custom): Next.js route handler → OAuth client-credentials → SitecoreAI Agent/Pages/Publishing/Sites APIs. Token cached in server memory; tenant identity comes from the
subclaim, not from a logged-in user.
Use when:
- The app needs an SDK call that has no SDK wrapper (e.g. Agent
/screenshot, Publishing job creation) — the only way to make that call is server-to-server against the underlying REST API. - The app is a service-to-service proxy with no logged-in Cloud Portal user (the automation client is the principal).
- You want both sides at once: subscribe to live page context and make backend calls without a PKCE login flow.
Don't use when:
- The call has an SDK wrapper (
xmc.*) — use 4a or 4b instead. Don't reinvent. - The app needs the user's identity / org / tenant in the access token — use 4c (Auth0 PKCE).
- The call must be made client-side from the iframe — Mode A only, see 4a.
Auth model:
- Client: portal-brokered (nothing to configure beyond Cloud Portal app registration).
- Server: OAuth 2.0 client-credentials per the
sitecoreai-authskill. Three-segment env vars (SITECORE_<API>_CLIENT_ID/SECRET, server-only — NOTNEXT_PUBLIC_*).
Scaffold: start from setup-marketplace-full-stack (you need the API routes), then skip the Auth0 PKCE post-scaffold steps — see that skill's "Auth modes" section for the exact substitution. Optionally remove the @auth0/auth0-react dep + components/providers/auth.tsx + custom-auth/ examples if you don't need PKCE at all.
Example: a Pages Context Panel screenshot app that subscribes to pages.context, sends the resulting pageId to its own app/api/screenshot/[pageId]/route.ts, which holds OAuth client-credentials server-side and proxies to the SitecoreAI Agent API /screenshot endpoint. Discovered as a real architecture while rebuilding that app (2026-05-02), not previously named in this taxonomy.
5. Authorization model (Auth0)
All Marketplace apps authenticate via Sitecore's Auth0 tenant. The auth model differs by architecture.
5a. Architecture 4a/4b (iframe) — portal-brokered
The portal handles auth. Your app does not configure Auth0 directly. Tokens never reach your app code — the postMessage bridge uses the portal's session.
What you do: nothing beyond registering the app in Cloud Portal with the right API access scopes. The Client SDK handles the rest.
5b. Architecture 4c (experimental server-to-server) — app-owned Auth0
You integrate Auth0 directly in your Next.js app.
Sitecore Auth0 tenant + required env vars:
AUTH0_DOMAIN=https://auth.sitecorecloud.io
AUTH0_AUDIENCE=https://api-webapp.sitecorecloud.io
AUTH0_SCOPE='openid profile email offline_access'
SITECORE_ORGANIZATION_ID=<from Cloud Portal>
SITECORE_TENANT_ID=<from standalone app URL after install — see the marketplace-sdk-testing-debug skill, § 5b>
Client-side example (Auth0 React):
import { useUser } from '@auth0/nextjs-auth0';
const { user } = useUser();
const xmc = await experimental_createXMCClient({
getAccessToken: () => getAccessTokenSilently(),
});
Server-side Auth0Client config (cookies + authorizationParameters): lives in the marketplace-sdk-testing-debug skill, § 4a. Do not reproduce here — it drifts.
5c. Required values (experimental)
| Value | What it's for | Where to capture |
|---|---|---|
organization_id | authorizationParameters.organization_id + env var SITECORE_ORGANIZATION_ID | Cloud Portal → your organization |
tenant_id | authorizationParameters.tenant_id + env var SITECORE_TENANT_ID | Standalone app URL after install (post-install step) |
sitecoreContextId | Every query: param of experimental_* calls | client.query('application.context') once from a Client-SDK page |
Capture procedures for each: the marketplace-sdk-testing-debug skill, § 5. The sitecoreContextId capture is a chicken-and-egg step — a small Client-SDK page reads application.context once, then you wire the value into the server-to-server flow.
5d. Iframe compatibility — mandatory
Iframe login under server-to-server enforces strict cookie policies: HTTPS, sameSite: 'none' + secure: true on session and transaction cookies, cross-origin third-party cookie rules. Full block + symptom table: the marketplace-sdk-testing-debug skill, § 4. Missing any rule makes auth "just not work" with no clear error.
6. Hosting
| App type | Who hosts | Requirements |
|---|---|---|
| Custom | You — any HTTPS-reachable host (Vercel, Azure, AWS, self-managed) | HTTPS, stable URL, matches the URL registered in Cloud Portal |
| Public (post-approval) | You still host — Marketplace listing points at your URL | Same + production-grade SLA expected |
Requirements (both):
- HTTPS with valid certificate — no self-signed certs for production
- Stable URL — URL changes require re-registering or updating the app in Cloud Portal
- CSP / cookie headers compatible with iframe embedding (sameSite, secure — see § 5d)
- Source lives in a public or private GitHub repo (Sitecore docs call this out for both custom and public apps)
7. Blok design system
Sitecore expects Marketplace apps to match the Blok design system (https://blok.sitecore.com/) for look-and-feel consistency.
- Custom apps: recommended but not enforced
- Public apps: effectively required for approval
What this means in practice:
- Use Blok tokens (colors, spacing, typography) rather than inventing a custom design language
- Match the portal's shell chrome where your app sits next to native panels
- Follow Blok accessibility conventions (WCAG AA minimum)
Integration: shadcn/ui scaffolds from the setup-scaffold skill ship with Blok-compatible defaults. If you diverge from shadcn, verify the chrome against Blok tokens before submission. See the blok-setup, blok-components, and blok-marketplace-integration skills for full guidance.
8. Public app submission checklist
Only required for phase 7–9 of the public-app lifecycle. From prepare-to-submit-a-public-app-for-approval.html:
- App name and description match Marketplace listing requirements (unique, descriptive, no trademark conflicts)
- Icon assets at required sizes
- Screenshots / walkthrough videos
- Privacy policy URL
- Support contact (email or URL)
- Blok compliance review passed
- Accessibility audit (WCAG AA)
- Production hosting live at stable URL
- All API access scopes minimized to what's actually used
- Tested in all registered extension points
Submission flow: Cloud Portal → App Studio → your app → Submit for approval. Sitecore reviews; approval can take days to weeks.
9. Common lifecycle pitfalls
9a. Starting to code before registering the app
Client SDK ClientSDK.init() handshakes with the portal and fails if the app isn't registered. Register in Cloud Portal first (step 1), then scaffold the code (step 4).
9b. Confusing architecture choice with scaffold choice
- Architecture 4a/4b scaffold decision: the
setup-scaffoldskill, § 2 vs § 3 (client-side-xmc.json vs full-stack-xmc.json) - Architecture 4c scaffold decision: typically a plain Next.js app with Auth0 +
experimental_*clients — no shadcn quickstart covers this yet
ADR the architecture decision before picking the scaffold.
9c. Treating experimental server-to-server as the "easier" path
It is not. You own the Auth0 integration, token refresh, iframe cookie config, and orgId/tenantId wiring. The iframe Client SDK path is significantly simpler. Only reach for experimental when the iframe model genuinely can't satisfy the requirement.
9d. Blok-compliance-as-afterthought
If you're building a public app, evaluate Blok from day one. Swapping out a custom design system at submission time is expensive. Use shadcn defaults or Blok-native components from the start.
9e. Missing orgId / tenantId for experimental mode
Both are required. tenantId is only visible after install — you open the standalone app from the portal shell and read the URL. Plan this as an explicit post-install step in your implementation plan.
10. Agent guidance
During discovery: Identify custom vs public during discovery. Public apps add 3–4 weeks of submission/Blok work — surface this in the requirements. Ask about target audience (internal-only vs ecosystem distribution) to decide.
During architecture: Produce an ADR covering (1) custom vs public, (2) architecture 4a/4b/4c, (3) auth model decision, (4) hosting. Record the registration values (app name, extension points, API scopes) as a planning artifact — they drive Cloud Portal setup. Do not plan both client-side iframe and server-to-server paths "for flexibility" — pick one.
During implementation planning: the plan's stack/dependencies section must include: (a) the exact Cloud Portal registration steps with required role, (b) the scaffold command from the setup-scaffold skill matching the chosen architecture, (c) required env vars (AUTH0_*, SITECORE_ORGANIZATION_ID, SITECORE_TENANT_ID if experimental), (d) HTTPS requirement for local dev (next dev --experimental-https), (e) the mandatory Auth0 cookie config if experimental mode is chosen. Reference the marketplace-sdk-testing-debug skill for the local dev loop.
During testing: Add a validation spike for iframe cookie flow — this is the single highest-impact silent failure in Marketplace apps. All verification runs in the real portal against a registered test app.
During implementation: Follow the architecture decision in the ADR. Do not cast between architectures mid-implementation. If you hit an auth error, check § 5d (HTTPS + cookie config) before debugging anywhere else.
Sitecore Marketplace Testing & Debugging
When to use
- You're setting up local development for a Marketplace app and hitting the Cloud Portal for the first time
- Auth "just isn't working" in the iframe and you need a debugging checklist
- You need to capture runtime values (organization ID, tenant ID, sitecoreContextId) for experimental server-to-server mode
- QA phase — verifying iframe behavior, extension-point constraints, error recovery
For Client SDK reference (ClientSDK.init, base API patterns, extension points) see the marketplace-sdk-client skill.
For XMC endpoints see the marketplace-sdk-xmc skill.
For AI skills specifics see the marketplace-sdk-ai skill.
For auth model background see the marketplace-sdk-lifecycle skill, § 5.
1. Local development — end-to-end setup
1a. Prerequisites
- Node.js 18+ and pnpm/npm
- Sitecore Cloud Portal account with
Organization AdminorOrganization Ownerrole - A registered SitecoreAI environment to install the test app into
- Ability to run your app on HTTPS localhost (see § 3)
1b. Six-step setup
1. Register a test app in Cloud Portal → App Studio
2. Configure dev URL → https://localhost:3000
3. Enable all extension points + all API access (for dev)
4. Install the test app into your SitecoreAI environment
5. Scaffold and run your app with HTTPS
6. Open from portal shell → your iframe loads the app
Detailed walkthrough of each step in the sections below.
2. Registering a test app (distinct from production)
Always register a separate app for testing, never repurpose the production app.
2a. Naming
Prefix or suffix test apps so they can't be confused:
Test application— docs-recommended plain test app<Project> — DEV— per-project dev app<Project> — QA— per-project QA app
2b. What to configure for a test app
| Field | Dev/QA value | Production value |
|---|---|---|
| App URL | https://localhost:3000 (or your dev tunnel URL) | Production HTTPS URL |
| Extension points | All — easier to switch contexts during dev | Only what you ship |
| API access | All — don't let permission errors confuse bug hunts | Minimized to what's used |
| User access | Only you — don't grant to org users | As appropriate for the release |
| Environment binding | A sandbox SitecoreAI environment | Production environment |
Rationale: a permissive test app removes an entire class of "why doesn't this work" questions. You can tighten permissions later when you register the production app.
2c. Cleanup
- Uninstall the test app when you're done with a project
- Don't let stale test apps accumulate — they clutter the org and may outlive their configured users
3. HTTPS on localhost — mandatory for full-stack, not for client-side
Scope matters. HTTPS locally is only required for Scaffold 3 full-stack apps (or Mode B experimental_create*Client flows) where your app serves auth cookies at its own origin — those cookies carry SameSite=None; Secure and secure cookies cannot be set over HTTP.
Scaffold 2 client-side Mode A apps work fine over plain HTTP. The app sets no cookies at its own origin; auth is portal-brokered via postMessage. All you need on the client-side path is the Chrome Local Network Access headers (see references/https-traps.md § 3) — no HTTPS, no mkcert, no cert-trust dance.
If you're unsure: start on HTTP. Only flip to HTTPS (and accept the complexity below) when you hit "cookies not being set" in § 4 because your app owns an Auth0 server.
3a. Next.js dev server with HTTPS (full-stack / Mode B only)
# Next.js 13.5+
next dev --experimental-https --turbopack
# Alternatives if you need a stable cert: mkcert, caddy, traefik in front of localhost
Set env:
APP_BASE_URL=https://localhost:3000
Post-scaffold dev-script patch (Scaffold 3 only): the shadcn quickstart ships next dev --turbopack without the --experimental-https flag. Edit package.json → scripts.dev to include --experimental-https before running against a real portal. Client-side Scaffold 2 apps keep the plain HTTP script and rely on the Chrome Local Network Access headers documented in references/https-traps.md instead.
3a-bis through 3a-quater — three HTTPS-mode traps
Three failure modes bite when running an HTTPS dev server against the real Cloud Portal:
- mkcert + the Windows non-interactive trap (Scaffold 3 only) — Next's
--experimental-httpssilently falls back to HTTP ifmkcert -installcan't elevate. Runmkcert -installfrom an elevated PowerShell, or pre-generate the cert manually. - Self-signed cert rejected inside iframe →
chrome-error://chromewebdata/(Scaffold 3 only) — Chrome's click-through "Proceed Anyway" grants trust only for the exact top-level navigation, not for iframe subresource loads from a public origin. Either install the mkcert CA into the system trust store, or tunnel viacloudflared/ngrokfor a public-CA-signed URL. - Chrome's Local Network Access block (both Scaffolds) — public-origin pages loading
localhost:*iframes are blocked unless the dev server advertises consent viaAccess-Control-Allow-Private-Network: trueheaders. Add the four-header block tonext.config.mjs.
For the full diagnostic walkthrough — symptoms, exact error messages in console, headers config, the * origin + credentials trap — see references/https-traps.md. The reference is the canonical one-stop debugging doc; the SKILL.md keeps just the rule + the pointer.
3b. If you need a proper hostname (not localhost)
Add to your hosts file (/etc/hosts on Unix, C:\Windows\System32\drivers\etc\hosts on Windows):
127.0.0.1 myapp.local
Then use https://myapp.local:3000 in both APP_BASE_URL and the Cloud Portal dev URL. Certificate must cover the hostname — mkcert myapp.local is the quickest path.
3c. Verifying HTTPS is really working
In browser devtools → Application → Cookies → your app origin, cookies must have:
Securecolumn: yesSameSitecolumn:None
If either is missing, the cookie config (see § 4) hasn't been applied.
4. Iframe cookie configuration — the #1 silent failure
Auth inside the iframe requires both session and transaction cookies to be cross-site compatible. Missing this is the most common cause of "login just doesn't work".
Required on session cookie AND transaction cookie:
{
sameSite: 'none', // allow cross-site
secure: true, // require HTTPS
}
4a. Next.js + Auth0 server
import { Auth0Client } from '@auth0/nextjs-auth0/server';
export const auth0 = new Auth0Client({
session: {
cookie: { sameSite: 'none', secure: true }, // MANDATORY
},
transactionCookie: { sameSite: 'none', secure: true }, // MANDATORY — often forgotten
authorizationParameters: {
scope: process.env.AUTH0_SCOPE,
audience: process.env.AUTH0_AUDIENCE,
organization_id: process.env.SITECORE_ORGANIZATION_ID,
tenant_id: process.env.SITECORE_TENANT_ID,
},
});
4b. Verification symptom table
| Symptom | Likely cause |
|---|---|
| Login redirect loops | sameSite: 'none' or secure: true missing on session cookie |
| Auth works outside iframe, fails inside | Transaction cookie not configured — only session cookie was set |
| Cookies appear then disappear on navigation | HTTPS not actually active (check cert in devtools) |
| "Organization not found" after login | organization_id missing from authorizationParameters |
401s on experimental_* calls even when logged in | Token audience mismatch — AUTH0_AUDIENCE must be https://api-webapp.sitecorecloud.io |
5. Capturing runtime values for experimental mode
Mode B (experimental_createXMCClient / experimental_createAIClient — see the marketplace-sdk-lifecycle skill, § 4c) needs three values that aren't available at development time. Capture them post-install.
5a. Organization ID
- Visible in Cloud Portal → your organization settings
- Set as env var:
SITECORE_ORGANIZATION_ID=<id> - Static per organization — capture once
5b. Tenant ID
- Install the test app first
- Open the standalone app from portal shell (the top-level portal navigation, not a deep link)
- Read the browser URL — tenant ID appears as a path segment or query param
- Set as env var:
SITECORE_TENANT_ID=<id> - Per environment — capture per environment you target
5c. sitecoreContextId
- Build a tiny Client SDK standalone page that just prints
application.context - Run the app once inside the iframe, open devtools, and read
resourceAccess[0].context.live(or.preview) - Persist in server-side config
// One-time capture snippet
const appCtx = await client.query('application.context');
console.log({
contextLive: appCtx.data?.resourceAccess?.[0]?.context?.live,
contextPreview: appCtx.data?.resourceAccess?.[0]?.context?.preview,
});
This capture step belongs in the implementation plan for any app using experimental mode — it is not automatic.
6. Debugging checklist — "the iframe isn't working"
When something breaks in the iframe and you don't know where to start, work this list in order:
6a. Is the app actually loading?
- Browser devtools → Network → filter to your app origin
- If zero requests: the portal iframe URL is wrong, or your app is down, or CSP is blocking
- If requests but 4xx/5xx: check app logs
6b. Is the iframe allowed to load?
- Devtools → Console → look for
X-Frame-Options/ CSPframe-ancestorserrors - Your hosting layer must allow framing from Sitecore portal origins
- Next.js: remove any
X-Frame-Options: DENYheaders; set CSPframe-ancestorsto include portal origin
6c. Is ClientSDK.init() handshaking?
- Add logging around
await ClientSDK.init({...}) - If it hangs > 30 s: handshake timeout — portal doesn't see the app's postMessage
- If it errors with
INVALID_ORIGIN: you passed a wrongoriginoption ortargetisn'twindow.parent - If it errors with
HANDSHAKE_FAILED: app is loaded standalone, not in the portal iframe — open it from the portal shell, not directly
6d. Are cookies being set?
- Devtools → Application → Cookies → your app origin
- Both session cookie and transaction cookie must have
SameSite=None; Secure - Missing = cookie config wrong (§ 4)
- Present but cleared on navigation = HTTPS not active or cert invalid
6e. Is auth flowing?
- Devtools → Network → filter
auth0/sitecorecloud.io - Follow the OAuth redirect chain — it should return to your
APP_BASE_URL/auth/callback - If redirect to non-HTTPS:
APP_BASE_URLmisconfigured - 401 response post-callback:
audienceororganization_idwrong
6f. Are SDK calls succeeding?
- Log the full result object, not just
.data:const result = await client.query('xmc.sites.listSites', opts); console.log(JSON.stringify(result, null, 2)); isError: true+error.codetells you which error class (see themarketplace-sdk-clientskill, § 8f)TOKEN_ERROR— auth config wrong; re-check § 4METHOD_NOT_FOUND— module not registered; passmodules: [XMC]or[AI]to initEXECUTION_ERROR— host-side failure; logerror.messageand contact Sitecore support if reproducibleSyntaxError: Unexpected end of JSON input/Failed to execute 'json' on 'Response': Unexpected end of JSON inputonai.skills.generateBrandReview→ oversized base64 payload. Bridge or AI backend returns empty body → SDK JSON.parse throws. See themarketplace-sdk-aiskill, § 9f. Shrink or host-externally the uploaded file.
6g. Is subscription cleanup happening?
- Watch-mode / hot reload can leak subscriptions
- Wrap
client.subscribe(...)→ always callunsubscribe()in ReactuseEffectcleanup - In devtools Performance tab, look for accumulating listeners
7. Browser-specific notes
| Browser | Gotcha |
|---|---|
| Chrome / Edge | Most forgiving; most bugs reproduce here first |
| Firefox | Stricter cookie partitioning — validate here after Chrome works |
| Safari | Strictest. Third-party cookies in iframes often blocked by default. If your app must work in Safari, test there explicitly, not just Chrome. |
| Private / Incognito | Third-party cookies usually disabled → auth will fail. Not a bug — document this. |
7a. iframe sandbox — downloads, popups, clipboard (2026-04-22)
Sitecore's Pages editor hosts Marketplace Context Panels inside an iframe with a restrictive sandbox= attribute. Know what is and isn't permitted before designing a capture / export / share flow.
Downloads are NOT allowed (pending upstream fix)
The Pages iframe sandbox currently does not include allow-downloads. Any client-side download attempt from inside the panel will silently fail:
<a href="blob:..." download="file.png">— the browser blocks the navigation triggered by the click; no file is saved, no error surfaces in the console.window.open(blobUrl)from inside the sandbox — same block.- Programmatic
a.click()after constructing an anchor — same block.
Sitecore has committed to adding allow-downloads soon. Expect this constraint to lift in a near-term Pages update. Until then:
Recommended workaround — escape the sandbox to a top-level tab:
window.open(blobUrl, '_blank', 'noopener,noreferrer');
This opens the blob URL in a top-level browser tab, outside the sandboxed iframe. The browser renders the PNG (or other resource) in the new tab and the user can right-click → Save Image As to disk. Requires allow-popups in the iframe sandbox — which IS present.
This is not a polished UX, but it's the only currently-working path to deliver a file from the panel to the user's disk. Track progress on the upstream sandbox fix and remove the workaround once allow-downloads ships.
Popups are allowed
allow-popups is present. window.open(url, '_blank', ...) works for:
- Escaping to a top-level tab (download workaround above).
- Opening help / docs URLs in a new tab.
- Auth popup flows if ever needed (not the current Marketplace auth model).
Clipboard requires the Permissions Policy, not the sandbox
Clipboard reads/writes (navigator.clipboard.writeText, navigator.clipboard.write(...) for binary blobs) are governed by the Permissions Policy (a separate browser gating mechanism), not the iframe sandbox. They require explicit user consent via the browser's permission prompt on first use, and they work independently of the download gate.
In practice this means: Copy (to clipboard) works inside the Sitecore Pages iframe today, even though Download (to disk) does not. A "Copy as PNG" or "Copy image to clipboard" button is a first-class path for moving content out of the panel until allow-downloads lands.
8. Pitfalls specific to testing
8a. Testing on HTTP localhost
The browser silently drops Secure cookies. Symptoms look like "login doesn't persist" with no console errors. Always HTTPS from day one.
8b. Running multiple dev apps on the same port
Browser caches cookies per origin. Two apps on https://localhost:3000 can interfere. Use different ports or hostnames (myapp-a.local, myapp-b.local) for parallel work.
8c. Stale test installs
Uninstall and reinstall when you change extension points or API access in Cloud Portal. The running iframe snapshots permissions at install time.
8d. Testing in the wrong environment
SitecoreAI environments aren't interchangeable. An app installed into dev-env-1 won't see content from dev-env-2. Verify the environment binding on the test app before blaming code.
9. Agent guidance
During implementation planning: the plan must include: (a) HTTPS dev command (next dev --experimental-https), (b) full Auth0 cookie config block (§ 4a), (c) test-app registration values (name, URL, extension points, API access), (d) a runtime-value capture task if experimental mode is used (orgId, tenantId, contextId — § 5). All dev and validation runs against the registered Cloud Portal test app — there is no mock path. Do not treat HTTPS / cookies as "obvious" — they are commonly missed.
During testing: Test scenarios must cover (a) fresh install in a clean org, (b) re-install after extension-point changes, (c) login flow in Chrome and Safari, (d) Private/Incognito as a "should show clear error" scenario, (e) subscription cleanup on navigation. All tests run against the real portal. Add a validation spike if the app uses WebGL, eval, or any iframe-sensitive feature.
During implementation: Before reporting "it's not working", walk § 6 in order. Most iframe/auth failures are caught at steps 6b–6d — a 10-minute devtools check beats hours of trial-and-error.
Sitecore Marketplace XMC Module
This skill is a catalog, not a contract. It documents which
xmc.*keys exist and what request params they accept. It does not document response envelopes (@hey-api/client-fetchwrappers,Sites.Host/Pages/Agentfield shapes), runtime availability per tenant, or tenant-side preconditions. Before writingclient.query("xmc.…"), open the SDK's declared types innode_modules/@sitecore-marketplace-sdk/xmc/dist/.../types.gen.d.tsand cite the.d.tspath inline. Mock fixtures must match the declared types. Verify in a real tenant before declaring shipped.
When to use
- The project uses
@sitecore-marketplace-sdk/xmc - The PRD calls for any SitecoreAI data operation (read sites/pages, run GraphQL, create/update content, move content between environments)
- Architect needs to select between module mode and experimental server-to-server mode for XMC calls
For Client SDK base (init, query/mutate/subscribe patterns) see the marketplace-sdk-client skill.
For auth & lifecycle (including experimental mode architecture decision) see the marketplace-sdk-lifecycle skill.
For AI skills module see the marketplace-sdk-ai skill.
For testing / debugging see the marketplace-sdk-testing-debug skill.
1. Package overview
| Package | Purpose |
|---|---|
@sitecore-marketplace-sdk/xmc | Type-safe access to SitecoreAI APIs — sites, pages, agent, authoring, preview, live, content-transfer, search |
Install (always latest): npm install @sitecore-marketplace-sdk/xmc@latest
The XMC module plugs into the Client SDK via modules: [XMC], extending its type maps with xmc.* keys. It can also be used standalone via experimental_createXMCClient (see § 2).
2. Two usage modes
| Mode | When | Init | Call shape | Token handling |
|---|---|---|---|---|
| A. Module mode | Inside a Client SDK iframe app (architectures 4a/4b in the marketplace-sdk-lifecycle skill) | ClientSDK.init({ modules: [XMC] }) | client.query('xmc.*', …) / client.mutate('xmc.*', …) | Portal-brokered via postMessage — no token in your code |
| B. Experimental direct | Standalone / server-to-server (architecture 4c in the marketplace-sdk-lifecycle skill) | experimental_createXMCClient({ getAccessToken }) | xmc.sites.*(…) etc. | You supply an Auth0 access token via getAccessToken |
Default: Mode A. Use Mode B only when the iframe path can't satisfy the requirement (cron jobs, microservices, server routes that need direct XMC access).
2a. Mode A — module registration
import { ClientSDK } from '@sitecore-marketplace-sdk/client';
import { XMC } from '@sitecore-marketplace-sdk/xmc';
const client = await ClientSDK.init({
target: window.parent,
modules: [XMC],
});
const result = await client.query('xmc.sites.listSites', {
params: { query: { sitecoreContextId } },
});
2b. Mode B — experimental direct client
import { experimental_createXMCClient } from '@sitecore-marketplace-sdk/xmc';
const xmc = await experimental_createXMCClient({
getAccessToken: async () => await getUserAccessToken(),
});
const languages = await xmc.sites.listLanguages({
query: { sitecoreContextId: 'your-context-id' }, // REQUIRED in Mode B
});
Full Auth0 config, iframe cookie requirements, and orgId/tenantId/contextId capture: see the marketplace-sdk-lifecycle skill, § 5. The same experimental_createAIClient pattern applies to the AI package — see the marketplace-sdk-ai skill, § 4.
2c. Multi-install / umbrella pattern (Standalone extension point)
The standalone extension point is bound to the organisation, not a single tenant. application.context.resourceAccess[] returns one entry per installation of this app across every SitecoreAI instance in the organisation — each entry carries its own live + preview sitecoreContextId. XMC calls in Mode A scope to whichever install you pass. This is the Cloud Portal umbrella pattern: one installed app reading/writing across many environments.
Every other extension point (xmc:fullscreen, xmc:pages:*, xmc:dashboardblocks) is bound to the single tenant the editor is operating in — resourceAccess[] typically has one entry (the current tenant) and there is no picker UX.
// 1. Enumerate installs (Standalone only exposes >1 in practice)
const appCtx = (await client.query('application.context')).data;
const installs = appCtx?.resourceAccess ?? [];
// installs[i] => {
// resourceId, tenantId, tenantName, tenantDisplayName?,
// context: { live, preview }, …extra portal-specific fields…
// }
// 2. Pick one (user dropdown, app logic, or fan-out)
const picked = installs[0];
const contextId = picked.context.live; // or .preview, per policy
// 3. XMC calls scope to the picked install's environment
const languages = await client.query('xmc.sites.listLanguages', {
params: { query: { sitecoreContextId: contextId } },
});
// 4. Fan-out across every install (umbrella probe)
const perInstall = await Promise.all(
installs.flatMap((i) =>
([i.context.live, i.context.preview].filter(Boolean) as string[]).map(
async (ctxId) => ({
tenant: i.tenantDisplayName ?? i.tenantName ?? i.tenantId,
contextId: ctxId,
result: await client.query('xmc.sites.listLanguages', {
params: { query: { sitecoreContextId: ctxId } },
}),
}),
),
),
);
Display names: prefer tenantDisplayName → tenantName → tenantId. The SDK type carries a [key: string]: any escape hatch, so portals may include richer fields (project name, region, environment kind). A single JSON dump of the raw entry during discovery is worth it — don't assume the minimal documented shape is the whole story.
Do not reach for experimental_createXMCClient at Standalone scope — Mode A works fine; experimental client is only for genuinely non-iframe contexts (cron jobs, server routes, microservices).
3. Calling convention
All XMC options use a consistent structure (hey-api client convention):
Mode A — options wrapped in params:
await client.query('xmc.sites.listSites', {
params: {
path: { siteId: '...' }, // URL path parameters
query: { sitecoreContextId: '...' }, // Query string parameters
},
});
await client.mutate('xmc.pages.createPage', {
params: {
query: { sitecoreContextId: '...' },
},
body: { // Request body
parentId: '...',
pageName: '...',
templateId: '...',
language: 'en',
},
});
Mode B — options at top level, no params: wrapper
await xmc.sites.retrieveSite({
path: { siteId: '...' },
query: { sitecoreContextId: '...' },
});
await xmc.pages.createPage({
body: { parentId, pageName, templateId, language: 'en' },
query: { sitecoreContextId },
});
Do not mix mode signatures in the same file. Pick a mode at architecture time and stick with it throughout.
4. Endpoint surfaces
XMC exposes seven endpoint groups — full key tables, params, and worked examples are in references/endpoints.md. Quick map of which group covers what:
| Group | What it covers | Verbs |
|---|---|---|
xmc.sites.* | Site listings, hierarchy, collections, languages, hosts | queries + a few mutations |
xmc.pages.* | Page CRUD, search, insert options, versions | queries + mutations (⚠ retrievePageState uses capitalized params; everything else lowercase) |
xmc.agent.* | High-level convenience endpoints — flat lists, screenshots, comprehensive page info | queries only |
xmc.authoring.graphql | GraphQL against the Authoring API | mutation (POST). Worked example: lazy item-name resolution at assets/lazy-item-resolution/ |
xmc.preview.graphql / xmc.live.graphql | GraphQL against Preview / Delivery edges | mutations (POST) |
xmc.contentTransfer.* | Cross-environment content migration | mutations — rarely used outside migration tools |
xmc.search.getConfigs | Search configurations | query |
Critical practical rule: every xmc.pages.* call — query AND mutation — must pass sitecoreContextId in query. The SDK types mark it optional; treat it as mandatory or mutations silently 200-and-do-nothing. Use the requireContextId() helper from § 6a.
For full key tables, the param-casing trap on retrievePageState, the GraphQL-is-a-mutation trap, and the lazy item-name-resolution worked example, see references/endpoints.md.
5. Type imports
The import paths for every request / response type the package exports are in references/type-imports.md. Derive shapes from the installed .d.ts; the reference tells you where each lives.
6. Common pitfalls
6a. sitecoreContextId is required for most XMC calls
Almost every XMC endpoint needs sitecoreContextId in params.query (Mode A) or query (Mode B). Get it from application.context:
const appCtx = await client.query('application.context');
const contextId = appCtx.data?.resourceAccess?.[0]?.context?.live;
// contextId is typed: string | undefined
context.live / context.preview are string | undefined in the generated types — the resulting contextId is string | undefined, never plain string.
Do NOT cast with as string. The shadcn quickstart (components/examples/built-in-auth/with-xmc/list-languages.tsx) ships const contextId = appCtx?.resourceAccess?.[0]?.context?.preview as string; — that's the Marketplace-rule anti-pattern. Calling an XMC endpoint with undefined cast to string sends sitecoreContextId=undefined on the wire; the API returns 401/403 and the cast hides the actual cause at compile time. Treat the cast as a post-scaffold edit, not a template.
Correct pattern — guard clause:
const appCtx = await client.query('application.context');
const contextId = appCtx.data?.resourceAccess?.[0]?.context?.live;
if (!contextId) {
throw new Error('Sitecore context unavailable — app not bound to a resource');
// or: setError('…'); return;
}
// contextId is narrowed to string from here on
await client.query('xmc.sites.listLanguages', {
params: { query: { sitecoreContextId: contextId } },
});
For a reusable helper, see the marketplace-sdk-client skill, § 4 "Getting sitecoreContextId" — the requireContextId() typed helper avoids repeating the guard across components.
.live vs .preview policy: .live is the delivery/published context; .preview is the editor/unpublished context. Use .live for production reads; use .preview when the app edits content the user hasn't published yet (typical for Pages Context Panel / Custom Field extension points). The quickstart picks .preview — replace with .live if the app reads published content.
Without this, calls fail with auth/permission errors. See the marketplace-sdk-lifecycle skill, § 5c, for the capture strategy (especially for Mode B where it must be persisted server-side).
6b. Multiple fetch strategies are a code smell
If your code tries 3+ different endpoints to get the same data:
- You don't know which endpoint is correct — check the tables above
- The correct endpoint requires
sitecoreContextIdand you're not passing it - The endpoint doesn't exist for your extension point type
Pick one endpoint per data need. Don't plan "fallback strategies" mixing agent + sites + raw GraphQL in the same function.
6c. GraphQL endpoints are mutations — AND the envelope is non-obvious
'xmc.authoring.graphql', 'xmc.preview.graphql', and 'xmc.live.graphql' are all client.mutate, not client.query — they're POST requests. TypeScript will reject them as queries; don't cast around this.
The envelope shape is the trap. The SDK's generated type declares body as a top-level field, but client.mutate(key, options)'s options parameter is a hey-api / openapi-fetch wrapper that nests body, query, and any path params under a single params key. body must live INSIDE params. And the response double-unwraps to result.data.data (outer = SDK wrapper, inner = GraphQL response body) — not single .data like other XMC mutations.
// CORRECT — body inside params, double-unwrap, no `as never` cast
const result = await client.mutate('xmc.authoring.graphql', {
params: {
query: { sitecoreContextId },
body: { query: GRAPHQL_QUERY, variables },
},
});
const root = result.data?.data as MyGraphqlResponse | undefined;
// WRONG — body at top level + single unwrap + `as never` cast hides the type error
const result = await client.mutate('xmc.authoring.graphql', {
params: { query: { sitecoreContextId } },
body: { query, variables }, // sends HTTP 400 with empty response body
} as never);
const data = (result as { data?: MyGraphqlResponse })?.data;
The wrong shape sends a malformed request to https://edge-platform.sitecorecloud.io/v1/authoring/graphql?sitecoreContextId=... and returns HTTP 400 with an empty body — no GraphQL errors payload to help diagnose. Two earlier apps shipped with this wrong shape before the issue was caught in a real-tenant capture. Verified against a real tenant on 2026-05-11.
Full reference: the marketplace-sdk-client skill's references/response-unwrap-matrix.md (and its § 8b).
For Authoring GraphQL mutation specifics (createItem rejects caller-supplied id, mutations wrap responses under { item { ... } }, rename requires dedicated renameItem, boolean wire format, aliased field(name:) accessor pattern), see references/authoring-graphql.md.
6d. Agent endpoints vs Sites/Pages endpoints
| Need | Use | Not |
|---|---|---|
| List all pages for a site | xmc.agent.sitesGetAllPagesBySite (flat list) | xmc.sites.retrieveSiteHierarchy (tree, more complex) |
| Components on a page | xmc.agent.pagesGetComponentsOnPage | Manual GraphQL layout parsing |
| Site list | xmc.agent.sitesGetSitesList (simple) | xmc.sites.listSites (also works, more params) |
Agent endpoints are generally the fastest path when they cover the use case. Drop to sites/pages for operations the agent layer doesn't expose.
6e. Mode A vs Mode B signatures are not interchangeable
Mode A wraps options in params: (e.g. { params: { path, query }, body }). Mode B puts them at the top level (e.g. { path, query, body }). Mixing will produce either TypeScript errors or silent runtime bugs.
6f. Mode B requires sitecoreContextId in every call
Mode A lets the portal supply context; Mode B does not. Every experimental_createXMCClient call must include query: { sitecoreContextId }. Missing it returns 401/403 even when the Auth0 token is valid.
6g. TypeScript — do NOT use as never / as any
The SDK is fully typed. If TypeScript complains about an xmc.* key, the cause is one of:
modules: [XMC]missing fromClientSDK.init()(Mode A)- Key string mistyped (case-sensitive)
- Wrong call verb (
queryvsmutate) for the endpoint
Fix the underlying issue. See the marketplace-sdk-client skill, § 8a, for the shared typing rule.
7. Recommended data-fetching pattern for graph/visualization apps
For apps that need to build a graph/tree of sites → pages → components:
// 1. Get context (guard before use — § 6a)
const appCtx = await client.query('application.context');
const contextId = appCtx.data?.resourceAccess?.[0]?.context?.live;
if (!contextId) throw new Error('Sitecore context unavailable');
// 2. Get sites (agent endpoint is simplest)
const sitesResult = await client.query('xmc.agent.sitesGetSitesList', {
params: { query: { sitecoreContextId: contextId } },
});
// 3. Get pages for a site
const pagesResult = await client.query('xmc.agent.sitesGetAllPagesBySite', {
params: {
path: { siteName },
query: { language: 'en', sitecoreContextId: contextId },
},
});
// 4. Get components per page (batch with Promise.allSettled)
const componentResults = await Promise.allSettled(
pages.map(page =>
client.query('xmc.agent.pagesGetComponentsOnPage', {
params: {
path: { pageId: page.id },
query: { language: 'en', sitecoreContextId: contextId },
},
})
)
);
Do not mix agent endpoints with raw GraphQL as fallback strategies in the same function. Pick one approach and commit to it.
8. Agent guidance
During architecture: When the architecture involves XMC data operations, select the correct endpoint namespace (agent / sites+pages / graphql) and document in an ADR. Do not plan "fallback" combinations. Pick Mode A unless the architecture requires server-to-server (see the marketplace-sdk-lifecycle skill, § 4c).
During implementation planning: Specify (a) which XMC keys, (b) exact param structures (params: { path, query }, body for Mode A; top-level for Mode B), (c) sitecoreContextId capture plan, (d) which mode. For Mode B, include tasks for Auth0 integration and token handling.
During testing: Test scenarios must cover each used endpoint: success, 404, auth error (missing sitecoreContextId), token expiry in Mode B. Verify pagination/batch limits on list endpoints. Test Authoring GraphQL specifically with a real schema — the mutation vs query distinction is a common miss.
During implementation: Use exact key strings. Wrap Mode A options in params:, don't wrap for Mode B. Unwrap Mode A responses with .data — except for module-key queries (xmc.*, ai.*) which double-unwrap .data.data, AND for GraphQL passthroughs (xmc.authoring.graphql, xmc.preview.graphql, xmc.live.graphql) which require body INSIDE params AND double-unwrap .data.data. See § 6c. For Authoring/Preview/Live GraphQL, use client.mutate, not client.query.
Sponsors
Details
- Marketplace
- Chris1415/sitecore-skills-pocs
- Source
- plugins/sitecore-marketplace
- Category
- Sitecore
- License
- Apache-2.0