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.
- 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 does.
Mutations: actions
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.
Fetching from components
- Use
useFetcheragainst your ownaction.*/resource.*routes (resourceRoutesin@/route-paths). - Use
useScapiFetcher(client, method, { params, body })from@/hooks/use-scapi-fetcherfor a small allowlisted set of Shopper calls without writing a route. It returns.load(),.submit(payload),.data,.errors,.success. The server enforces an allowlist insrc/lib/scapi/resource-policy.ts(for exampleshopperProducts.getProduct,shopperBasketsV2.getBasket,shopperSearch.getSearchSuggestions, and selectedshopperCustomersaddress and profile mutations). Anything else needs a dedicated route. See SCAPI-FETCHER.md. - Do not fetch in
useEffecton mount what the loader could fetch (see the performance review checklist instorefront-next:sfnext-performance). - Fetchers and raw
fetchcalls that do not go through a submission do not trigger revalidation; actions do, for every active loader.
Checklist
- Can the loader fetch this at request time? If yes, do it there.
- Is it critical?
await; otherwise return the promise with its own Suspense and a sized skeleton. - Did you request only the fields you render?
- Mutation errors:
createActionErrorwith anErrorCode, return withdata(..., { status }). - New shared fetch logic goes in
src/lib/api/*.server.tswith a test (storefront-next:sfnext-testing). - Run
pnpm typecheckandpnpm test.
Deeper: LOADERS.md.
Finding more
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.
Related Skills
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 API