sfnext-data-fetching
БесплатноБез исполняемых скриптовНе проверенLoad and mutate data in a Storefront Next project: route loaders that call SCAPI through createApiClients from @/lib/api-clients.server, critical versus…
от SalesforceCommerceCloud★ 58 звёзд на GitHubОб этом скилле
Storefront Next Data Fetching
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.
The rules (same as AGENTS.md)
- Fetch on the server in
loader(reads) andaction(writes). There is noclientLoaderorclientAction. - Classify every piece of data:
- Critical (needed for SEO, LCP, layout stability or the HTTP status):
awaitit in the loader. - Non-critical (below the fold, recommendations, reviews, secondary panels): start the request, do not await it, and return the unresolved promise so it streams.
- Interaction-driven (only after a click, hover or input): fetch on demand with a fetcher.
- Critical (needed for SEO, LCP, layout stability or the HTTP status):
- Never block a loader on non-critical data.
- Pass the promise through
loaderDataand read it under its own<Suspense>withuse()or<Await>. Keep the promise identity stable (compose it in the loader, neverPromise.allor.thenin render). - Export
shouldRevalidateon routes whose loaders depend on URL filters (seestorefront-next:sfnext-revalidation).
Loader with critical and streamed data
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.
SCAPI clients
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
Установить sfnext-data-fetching в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл sfnext-data-fetching?
Load and mutate data in a Storefront Next project: route loaders that call SCAPI through createApiClients from @/lib/api-clients.server, critical versus streamed (deferred) data, createBasketAction and BasketAction for cart actions, createActionError and ErrorCode, data() responses, useFetcher and the useScapiFetcher hook with its server allowlist, request-scoped dedupe and MRT timeouts, non-personalized SCAPI responses, shopper context, and custom API clients. Use for "fetch products in a loader", "stream data", "add a cart action", "call SCAPI from a component", "resource route", "NormalizedApiError", or "loader blocks the page". Do not use for route files or links (use `storefront-next:sfnext-routing`), when loaders re-run after actions (use `storefront-next:sfnext-revalidation`), Suspense/LCP tuning (use `storefront-next:sfnext-performance`), or defining SCAPI custom APIs (use `storefront-next:sfnext-scapi`).
Как установить скилл sfnext-data-fetching?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл sfnext-data-fetching запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic