TypeScript icon, indicating that this package has built-in type declarations

1.3.0 • Public • Published

📢 Hey there, Salesforce Commerce Cloud community!

We’re excited to hear your thoughts on your developer experience with PWA Kit and the Composable Storefront generally! Your feedback is incredibly valuable in helping us guide our roadmap and improve our offering.

📋 Take our quick survey here: Survey

Feel free to share this survey link with your colleagues, partners, or anyone who has experience with PWA Kit. Your input will help us shape the future of our development tools.

Thank you for being a part of our community and for your continuous support! 🙌

Commerce SDK React

A collection of react-query hooks for fetching, caching, and mutating data from the Salesforce B2C Commerce API (SCAPI).

🎯 Features

  • Shopper authentication & token management via SLAS
  • Server side data fetching (in conjuction with PWA Kit)
  • Phased Launch support (plugin_slas compatible)
  • Built-in caching for easy state management
    • automatic cache invalidations/updates via the library's built-in mutations
    • automatic cache key generation

⚙️ Installation

npm install @salesforce/commerce-sdk-react @tanstack/react-query

⚡️ Quickstart (PWA Kit v2.3.0+)

To integrate this library with your PWA Kit application you can use the CommerceApiProvider directly assuming that you use the withReactQuery higher order component to wrap your AppConfig component. Below is a snippet of how this is accomplished.

// app/components/_app-config/index.jsx

import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query'

const AppConfig = ({children}) => {
    return (

// Set configuration options for react query.
// NOTE: This configuration will be used both on the server-side and client-side.
// retry is always disabled on server side regardless of the value from the options
const options = {
    queryClientConfig: {
        defaultOptions: {
            queries: {
                retry: false
            mutations: {
                retry: false

export default withReactQuery(AppConfig, options)

⚡️ Quickstart (Generic React App)

You can use this library in any React application by creating a new QueryClient and wrap your application with QueryClientProvider. For example:

import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {QueryClient, QueryClientProvider} from '@tanstack/react-query'

const App = ({children}) => {
    const queryClient = new QueryClient()

    return (
        <QueryClientProvider client={queryClient}>

export default App

Shopper Authentication and Token Management

💡 This section assumes you have read and completed the Authorization for Shopper APIs guide.

To help reduce boilerplate code for managing shopper authentication, by default, this library automatically initializes shopper session and manages the tokens for developers. Currently, the library supports the Public Client login flow.

Shopper Session Initialization

On CommerceApiProvider mount, the provider initializes shopper session by initiating the SLAS Public Client login flow. The tokens are stored/managed/refreshed by the library.

Authenticate request queue

While the library is fetching/refreshing the access token, the network requests will queue up until there is a valid access token.

Login helpers

To leverage the managed shopper authentication feature, use the useAuthHelper hook for shopper login.


import {AuthHelpers, useAuthHelper} from '@salesforce/commerce-sdk-react'

const Example = () => {
    const register = useAuthHelper(AuthHelpers.Register)
    const login = useAuthHelper(AuthHelpers.LoginRegisteredUserB2C)
    const logout = useAuthHelper(AuthHelpers.LogOut)

    return <button onClick={() => {
        login.mutate({username: 'kevin', password: 'pa$$word'})

Externally Managed Shopper Authentication

You have the option of handling shopper authentication externally, by providing a SLAS access token. This is useful if you plan on using this library in an application where the authentication mechanism is different.

const MyComponent = ({children}) => {
    return <CommerceApiProvider fetchedToken="xxxxxxxxxxxx">{children}</CommerceApiProvider>


The majority of hooks provided in this library are built on top of the useQuery and the useMutation hook from react-query. React-query provides a declarative way for fetching and updating data. This library takes advantage of the features provided by react-query and combine with the commerce-sdk-isomorphic API client to create a collection of hooks to simplify data fetching for SCAPI.

The hooks can be categorized into Query hooks and Mutation hooks.

Query hooks

The query hooks correspond to the http GET endpoints from the SCAPI. The query hooks follow the signature pattern:

use<EntityName>(CommerceClientOptions, ReactQueryOptions)

Both the required and optional parameters for the underlying commerce-sdk-isomorphic call is passed as the first parameter:

import {useProduct} from '@salesforce/commerce-sdk-react'

const Example = () => {
    const query = useProduct({
        parameters: {
            id: '25592770M',
            locale: 'en-US'

    return (
            <p>isLoading: {query.isLoading}</p>
            <p>name: {query.data?.name}</p>

The second parameter is the react-query query options, for more detail, read useQuery reference.

import {useBasket} from '@salesforce/commerce-sdk-react'

const onServer = typeof window === undefined

const Example = ({basketId}) => {
    const query = useBasket(
            parameters: {
                basketId: basketId
            // A common use case for `enabled` is
            // to conditionally fetch based on environment
            enabled: !onServer && basketId

Mutation hooks

The query hooks correspond to the http POST, PUT, PATCH, DELETE endpoints from the SCAPI. The mutation hooks follow the signature pattern:


For example, the ShopperBaskets API has a number of endpoints, one of them being the addItemToBasket endpoint (POST /baskets/{basketId}/items).

import {useShopperBasketsMutation} from '@salesforce/commerce-sdk-react'

const Example = ({basketId}) => {
    // Typescript IDE intellisense for available options
    const addItemToBasket = useShopperBasketsMutation('addItemToBasket')

    return (
            onClick={() =>
                    parameters: {
                    body: {
                        productId: '25592770M',
                        price: 55,
                        quantity: 1

You could also import the mutation options as a constant like:

import {useShopperBasketsMutation, ShopperBasketsMutations} from '@salesforce/commerce-sdk-react'

const Example = ({basketId}) => {
    // this works
    const addItemToBasket = useShopperBasketsMutation('addItemToBasket')

    // this also works
    const addItemToBasket = useShopperBasketsMutation(ShopperBasketsMutations.AddItemToBasket)
    return ...

Cache Invalidations and Updates

Since mutations changes data on the server, the cache entries that are potentially affected by the mutation is automatically invalidated.

For example, an addItemToBasket mutation automatically update useBasket and useCustomerBaskets query cache, because the mutation result contains the information for the updated basket. In other cases, when the mutation response do not have the updated data, the library will invalidate the cache and trigger a re-fetch. For the DELETE endpoints, the library removes the cache entries on successful mutations.

💡 Debugging hint: install and include @tanstack/react-query-devtools in your React app to see the queries (inspect the query states and cache keys).


Besides the collection of query hooks and mutation hooks, here are some ultility hooks to help you interact with SCAPI.


This hook returns a set of SCAPI clients, which are already initialized using the configurations passed to the provider. Note: this hook doesn't automatically include auth headers.

import {useCommerceApi, useAccessToken} from '@salesforce/commerce-sdk-react'

const Example = () => {
    const api = useCommerceApi()
    const {getTokenWhenReady} = useAccessToken()

    const fetchProducts = async () => {
        const token = await getTokenWhenReady()
        const products = await api.shopperProducts.getProducts({
            parameters: {ids: ids.join(',')},
            headers: {
                Authorization: `Bearer ${token}`
        return products


useAccessToken() => {token: String, getTokenWhenReady: Promise}

This ultility hook give access to the managed SLAS access token.


useCustomerId() => null | string


useCustomerId() => null | 'guest' | 'registered'


useEncUserId() => {encUserId: String, getEncUserIdWhenReady: Promise}


useUsid() => {usid: String, getUsidWhenReady: Promise}


  • Optimistic update support
  • SLAS private client support

Useful Links:


Current Tags

Version History

Package Sidebar


npm i @salesforce/commerce-sdk-react

Weekly Downloads





See license in LICENSE

Unpacked Size

461 kB

Total Files


Last publish


  • dme722
  • nolanlawson
  • ire-npm-team-user
  • jburnie
  • abirchfieldsfdc
  • dlouvton
  • mobify
  • jmsjtu
  • jasonschroeder-sfdc
  • packagellama
  • maward
  • danielshox
  • duane.chew
  • dferro
  • jcourtner
  • jye-sf
  • adirasanam
  • hkii
  • iamaziz
  • dbreese-salesforce
  • ashokrudraraju
  • dhersam
  • demianbrecht
  • mbettio
  • damilareolowoniyi
  • mmadialagan
  • mjrust
  • salesforce-releases
  • mpsenn
  • kevinv11n
  • byao
  • pmdartus
  • ekashida
  • gr8gatsby
  • ravi.jayaramappa
  • apapko
  • jleen-sfdc
  • jqian
  • cwallsf
  • dhagberg-sf
  • khawkins
  • amphro
  • jodarove
  • sfdctaka
  • fernomac
  • jimjag
  • ivarley
  • jbartolotta-sfdc