Salesforce Commerce Cloud PWA Kit

repository·develop·Indexed 18 days ago

https://github.com/salesforcecommercecloud/pwa-kit

A storefront technology for headless commerce that enables developers to build flexible shopping experiences using React and Salesforce Commerce APIs. It includes the @salesforce/commerce-sdk-react for managing SCAPI requests via query and mutation hooks, shopper authentication via useAuthHelper, and integration with @tanstack/react-query for cache management.

Tokens
152.2K
Snippets
449
Records
592
Agent score
60%

What's inside PWA Kit

  1. What is PWA Kit MCP Server?

    develop

    PWA-Kit-MCP is a local STDIO Model Context Protocol (MCP) server designed to enhance the Salesforce Commerce Cloud PWA Kit development lifecycle. It allows AI agents (like those in Cursor IDE) to interact with your local development environment to perform tasks such as project creation, page generation, following best practices, and running site audits.

    Note: This feature is currently in developer preview. Commands and parameters are subject to change without notice.

  2. Overview of template-mrt-reference-app

    develop
    The template-mrt-reference-app is a reference application used by the Managed Runtime Team (MRT) to validate platform features, such as TLS versions, deployment success, and proxy behavior. It serves as a minimal implementation layer over the core SDKs required for all MRT users. While MRT is primarily used for hosting React applications, this template is designed to test universal platform features that apply regardless of the specific framework being used.
  3. Coexistence of Distributed Tracing and server_timing

    develop

    Distributed Tracing (DT) is designed to run alongside the existing server_timing instrumentation without conflict.

    Featureserver_timingDistributed Tracing
    PropagatorGlobal (B3Propagator)Instance-based (W3CTraceContextPropagator)
    ProviderGlobal (provider.register())Non-global (provider.getTracer())
    Context ManagerAsyncHooksContextManagerAsyncHooksContextManager
    Activation FlagotelConfig.enabled && shouldTrackPerformanceotelConfig.enabled

    Because DT uses a local instance of the W3CTraceContextPropagator rather than setting a global one, it does not disturb the B3 propagation used by server_timing. Both share the same AsyncHooksContextManager type, where the first-writer-wins approach ensures safe operation.

  4. How Outbound Propagation (SSR to SCAPI) Works

    develop

    To ensure end-to-end visibility, PWA Kit forwards the trace context from the SSR process to outbound Shopper Commerce API (SCAPI) and Shopper Login & API Access Service (SLAS) calls.

    1. Context Capture: Inside the ssr.render span, withServerSpan writes the active traceparent to res.locals.traceparent and sets it as a response header.
    2. Header Forwarding: The application template (e.g., template-retail-react-app) must forward res.locals.traceparent via the headers prop on the CommerceApiProvider in _app-config/index.jsx.
    3. SDK Execution: The commerce-sdk-react library picks up this header and forwards it verbatim in the outbound request.

    Important: This mechanism is designed so that the client bundle ships no OpenTelemetry code. The commerce-sdk-react library does not import @opentelemetry/api; it simply passes the string through, ensuring no OTel overhead in the browser.

  5. How Trusted Agent login works with COOP

    develop

    When Cross-Origin-Opener-Policy: same-origin is active, the browser moves the login popup into a new browsing context group, severing the opener's reference to it.

    To resolve this, the system uses three components:

    1. commerce-sdk-react hooks: useTrustedAgent listens for results via postMessage (with BroadcastChannel fallback) instead of relying on popup.closed. useTrustedAgentPopupCallback is used on the callback page to deliver the result.
    2. The /callback page: A page (typically app/pages/login-redirect/index.jsx) that mounts useTrustedAgentPopupCallback to post the code and state back to the storefront.
    3. Server-side handling: The server must preserve the code when state is present and serve that specific request with Cache-Control: no-store to prevent sensitive OAuth codes from being cached by CDNs.
  6. How cache invalidation works with mutations

    develop

    The library automatically manages cache invalidation to ensure data consistency.

    1. Automatic Updates: If a mutation response (like addItemToBasket) contains the updated entity data, the library automatically updates the relevant query caches (e.g., useBasket).
    2. Automatic Re-fetching: If the mutation response does not contain the updated data, the library invalidates the cache and triggers a background re-fetch.
    3. Deletion: For DELETE endpoints, the library removes the corresponding cache entries upon a successful mutation.

    Tip: Use @tanstack/react-query-devtools to inspect query states and cache keys during development.

  7. How Order Returns work

    develop

    Registered shoppers can return eligible items via a Return Items modal. The process follows these steps:

    1. Eligibility Check: The UI verifies the shopper is registered, owns the order, the order has omsData, and at least one item has omsData.quantityAvailableToReturn > 0.
    2. Metadata Loading: The page calls useOmsMetaData to fetch returnReasonCodes. If this fails, the Reason column is hidden, and the shopper proceeds without a reason (the server applies the OMS default).
    3. Selection: The shopper selects items, quantities (capped by availability), and a reason.
    4. Request Construction: buildReturnProductItems(selection, defaultReasonCode) generates the productItems array for the OmsReturnOrderRequest. If the default reason is used, the reason field is omitted from the request.
    5. Submission: The request is sent via useShopperOrdersMutation(ShopperOrdersMutations.ReturnOmsOrder) (POST .../actions/oms-return-order).
    6. Success: The page refetches the order to update the status badge and returnable quantities.
  8. How Order Cancellation works

    develop

    Registered shoppers can cancel an order that has not yet started fulfillment.

    Eligibility Requirements:

    • The shopper must be registered and own the order.
    • The order must have omsData.
    • All-or-nothing rule: Every single item in the order must be fully cancellable (item.omsData.quantityAvailableToCancel === item.omsData.quantityOrdered). If any unit has shipped, the entire order is ineligible for cancellation.

    Process:

    1. The shopper confirms via the CancelOrderModal.
    2. The request is submitted via useShopperOrdersMutation(ShopperOrdersMutations.CancelOmsOrder) (POST .../actions/oms-cancel-order).
    3. On success, an "Order cancelled" alert is shown and the status badge updates to Canceled.
    4. Error Handling: Unlike returns, cancellation error handling keys off the HTTP status alone. A 404 or 409 is considered terminal, causing the cancellation button to be permanently disabled with an explanatory hint. Other errors are treated as retryable.
  9. Understand locale selection logic

    develop

    The app determines the target locale by comparing two sets:

    1. App-supported locales: Defined in config/sites.js under l10n.supportedLocales.
    2. User-preferred locales: The preferences of the visitor (implemented by the developer within the _app component).

    Selection Process:

    • If a match is found between the user's preferred locales and the app's supported locales, that match is used.
    • If no match is found, the app falls back to the locale used in the inline defaultMessage strings.