Sfnext data fetching

From SalesforceCommerceCloud/b2c-developer-tooling · View interactive version

Sfnext data fetching is an AI agent skill from the GitHub repository SalesforceCommerceCloud/b2c-developer-tooling. 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 t

How to use this skill

Skill file

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)

  1. Fetch on the server in loader (reads) and action (writes). There is no clientLoader or clientAction.
  2. Classify every piece of data:
  1. Never block a loader on non-critical data.
  2. Pass the promise through 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).
  3. Export shouldRevalidate on routes whose loaders depend on URL filters (see storefront-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

Checklist

  1. Can the loader fetch this at request time? If yes, do it there.
  2. Is it critical? await; otherwise return the promise with its own Suspense and a sized skeleton.
  3. Did you request only the fields you render?
  4. Mutation errors: createActionError with an ErrorCode, return with data(..., { status }).
  5. New shared fetch logic goes in src/lib/api/*.server.ts with a test (storefront-next:sfnext-testing).
  6. Run pnpm typecheck and pnpm 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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.