/storefront-next:sfnext-data-fetchingfrom storefront-next
Load and mutate data in Storefront Next using route loaders and actions with SCAPI. Covers critical vs streamed data, cart actions, useScapiFetcher, and request-scoped dedupe.
Ships in storefront-next. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
All data comes from the server. Loaders and actions run on the server with the shopper's session; the browser never calls SCAPI directly. Your project ships docs/README-DATA.md, docs/README-SUSPENSE.md, docs/README-SCAPI-NON-PERSONALIZED-RESPONSES.md and docs/README-SHOPPER-CONTEXT.md, plus the "Performance & Data Rules" in AGENTS.md; this skill is the quick path, those are authoritative.
loader (reads) and action (writes). There is no clientLoader or clientAction.await it in the loader.loaderData and read it under its own <Suspense> with use() or <Await>. Keep the promise identity stable (compose it in the loader, never Promise.all or .then in render).shouldRevalidate on routes whose loaders depend on URL filters (see storefront-next:sfnext-revalidation).import { Suspense } from 'react';
import { Await } from 'react-router';
import type { Route } from './+types/_app.example';
import { createApiClients } from '@/lib/api-clients.server';
import { fetchProductById } from '@/lib/api/products.server';
import { NormalizedApiError } from '@/lib/api/normalized-api-error';
export async function loader({ context, params }: Route.LoaderArgs) {
const clients = createApiClients(context);
// Non-critical: start now, do not await.
const related = clients.shopperSearch
.productSearch({ params: { query: { q: 'shirt', limit: 8 } } })
.then(({ data }) => data.hits ?? []);
// Critical: needed for status, SEO and LCP.
try {
const product = await fetchProductById(context, params.id ?? '', { expand: ['images', 'prices'] });
if (!product) throw new Response('Not found', { status: 404 });
return { product, related };
} catch (e) {
if (e instanceof NormalizedApiError && e.status) throw new Response(e.message, { status: e.status });
throw e;
}
}
export default function Example({ loaderData }: Route.ComponentProps) {
return (
<>
<h1>{loaderData.product.name}</h1>
<Suspense fallback={<div className="h-40" aria-busy="true" />}>
<Await resolve={loaderData.related}>{(hits) => <ul>{hits.map((h) => <li key={h.productId}>{h.productName}</li>)}</ul>}</Await>
</Suspense>
</>
);
}
Real precedent: src/routes/_app.p.$.tsx awaits the product (404 becomes throw new Response(..., { status: 404 })) and streams the Page Designer page, schema and extras; src/components/product-grid/deferred.tsx is the streamed-grid pattern.
createApiClients(context) from @/lib/api-clients.server returns AppClients: every generated Shopper API client (shopperProducts, shopperSearch, shopperBasketsV2, shopperCustomers, shopperOrders, shopperLogin, and more) plus generated clients for your custom APIs (@/scapi/custom-clients). Call shape:
const { data } = await clients.shopperBasketsV2.addItemToBasket({
params: { path: { basketId }, query: {} },
body: [{ productId, quantity: 1 }], // body is a sibling of params; this endpoint takes an array
});
Results are { data }; failures throw. Prefer the thin wrappers in src/lib/api/*.server.ts (fetchProductById, fetchProductsByIds which chunks to the 24-id limit, category, search, order, customer and basket helpers): they log and rethrow as NormalizedApiError (@/lib/api/normalized-api-error, with .status and .cause). Add new wrappers there rather than calling clients inline in many routes.
The clients already wrap fetch with request-scoped GET/HEAD dedupe (identical calls in one request share one response; any mutation clears the cache), a hard timeout from the MRT_REQUEST_TIMEOUT environment variable when set, and a health observer that logs 429 and load-status headers. Do not re-implement them. More: API-CLIENTS.md.
Trim payloads: pass only the expand/select values you render. Availability is cached about 60 seconds and prices/promotions about 15 minutes, so short-TTL data is a good candidate for streaming. Shopper-agnostic responses can be cached using the policy in src/lib/scapi/non-personalized-response-policy.server.ts (see the shipped README-SCAPI-NON-PERSONALIZED-RESPONSES); request personalized: 'none' only where the response truly is the same for all shoppers, as the navigation loader in _app.tsx does.
Prefer an action.* route and a <Form> (navigating) or useFetcher (non-navigating).
Basket mutations use the factory, which loads the basket, parses FormData, catches errors and wraps the result:
// src/routes/action.example-remove-item.ts
import { data } from 'react-router';
import { BasketAction, createBasketAction } from '@/lib/cart/basket-action.server';
import { createActionError } from '@/lib/action-error-helpers.server';
import { ErrorCode } from '@/lib/error-codes';
export const action = createBasketAction(
{ method: 'POST', action: BasketAction.CartItemRemove, parse: (fd) => ({ itemId: String(fd.get('itemId') ?? '') }) },
async ({ input, basketId, clients }) => {
if (!input.itemId) {
return data({ success: false, error: createActionError({ code: ErrorCode.REQUIRED_FIELD, message: 'itemId is required' }) }, { status: 400 });
}
const { data: basket } = await clients.shopperBasketsV2.removeItemFromBasket({ params: { path: { basketId, itemId: input.itemId } } });
return basket; // factory returns { success: true, basket } and syncs the basket resource
}
);
Return the updated Basket for success. Return data(payload, { status }) for validation errors (use data() from react-router, not Response.json). Thrown SCAPI 4xx errors pass their status through; others become 500. Available BasketAction values are listed in src/lib/cart/basket-action.server.ts. See the existing action.cart-item-*.tsx files. Details and non-basket actions: ACTIONS.md.
useFetcher against your own action.*/resource.* routes (resourceRoutes in @/route-paths).useScapiFetcher(client, method, { params, body }) from @/hooks/use-scapi-fetcher for a small allowlisted set of Shopper calls without writing a route. It returns .load(), .submit(payload), .data, .errors, .success. The server enforces an allowlist in src/lib/scapi/resource-policy.ts (for example shopperProducts.getProduct, shopperBasketsV2.getBasket, shopperSearch.getSearchSuggestions, and selected shopperCustomers address and profile mutations). Anything else needs a dedicated route. See SCAPI-FETCHER.md.useEffect on mount what the loader could fetch (see the performance review checklist in storefront-next:sfnext-performance).fetch calls that do not go through a submission do not trigger revalidation; actions do, for every active loader.await; otherwise return the promise with its own Suspense and a sized skeleton.createActionError with an ErrorCode, return with data(..., { status }).src/lib/api/*.server.ts with a test (storefront-next:sfnext-testing).pnpm typecheck and pnpm test.Deeper: LOADERS.md.
Open AGENTS.md ("Key Documentation") and docs/README-DATA.md in your project. Search product docs with b2c docs search "<term>" or the docs_search MCP tool.
storefront-next:sfnext-routing - route files and linksstorefront-next:sfnext-revalidation - avoid wasted loader re-runs after actionsstorefront-next:sfnext-performance - Suspense placement, LCP, review checkliststorefront-next:sfnext-state-management - basket provider and client statestorefront-next:sfnext-scapi - SCAPI access and custom APIsstorefront-next:sfnext-authentication - sessions behind loadersb2c-cli:b2c-scapi-custom - inspect custom API endpointsb2c:b2c-custom-api-development - build a custom APIWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub salesforcecommercecloud/b2c-developer-tooling --plugin storefront-next25 skills in this plugin
/sfnext-accessibilityBuild and fix accessible UI in a Storefront Next storefront (WCAG 2.1 AA): jsx-a11y lint findings, missing accessible names and labels, form error association, dialog focus management, aria-live status messages, keyboard behavior, color contrast, and verifying fixes with Storybook a11y/play() tests and the e2e axe scan with its baseline. Use for "accessibility", "a11y", "WCAG", "screen reader", "aria-label", "focus trap", "axe violation", pnpm lint:a11y, pnpm a11y, a11y-baseline.json, skip-a11y, STORYBOOK_A11Y_TEST_MODE, or an accessibility audit finding to fix. Do not use for general lint/typecheck gates (use `storefront-next:sfnext-quality-gates`), writing non-accessibility tests (use `storefront-next:sfnext-testing`), or color/token design (use `storefront-next:sfnext-theming`)./sfnext-analytics-consentStorefront Next analytics: engagement adapters (Einstein, Active Data, Data 360), adding a custom adapter, tracking consent gating, PageViewTracker, useAnalytics events, and first-touch attribution (dw_attribution). Use when configuring engagement.adapters in config.server.ts, writing an adapter with hasConsent, registering it in initializeEngagementAdapters, wiring the consent banner (trackingConsent, consentCategories, dw_dnt), firing trackViewProduct/trackCartItemAdd events, debugging why no analytics events are sent, or passing campaign attribution to orders. Do not use for general config loading or env vars (use `storefront-next:sfnext-configuration`), CSP/script allowlisting of third-party tags (use `storefront-next:sfnext-security`), or SEO meta/JSON-LD (use `storefront-next:sfnext-seo`).Other plugins' skills for the same job