@salesforce/commerce-sdk-react
TypeScript icon, indicating that this package has built-in type declarations

3.4.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).

⚠️ Planned API Changes ⚠️

Shopper Context

Starting July 31st 2024, all endpoints in the Shopper context API will require the siteId parameter for new customers. This field is marked as optional for backward compatibility and will be changed to mandatory tentatively by January 2025. You can read more about the planned change here in the notes section.

Shopper Login (SLAS)

SLAS will soon require new tenants to pass channel_id as an argument for retrieving guest access tokens. You can read more about the planned change here.

Please be aware that existing tenants are on a temporary allow list and will see no immediate disruption to service. We do ask that all users seek to adhere to the channel_id requirement before the end of August to enhance your security posture before the holiday peak season.

In practice, we recommend:

  • For customers using the SLAS helpers with a private client, it is recommended to upgrade to v3.0.0 of the commerce-sdk-react.

🎯 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 v3.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}) => {
    const headers = {
        'correlation-id': correlationId
    }

    return (
        <CommerceApiProvider
            clientId="12345678-1234-1234-1234-123412341234"
            organizationId="f_ecom_aaaa_001"
            proxy="localhost:3000/mobify/proxy/api"
            redirectURI="localhost:3000/callback"
            siteId="RefArch"
            shortCode="12345678"
            locale="en-US"
            currency="USD"
            headers={headers}
            // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows.
            // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting.
            // enablePWAKitPrivateClient={true}
            logger={createLogger({packageName: 'commerce-sdk-react'})}
        >
            {children}
        </CommerceApiProvider>
    )
}

// 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}>
            <CommerceApiProvider
                clientId="12345678-1234-1234-1234-123412341234"
                organizationId="f_ecom_aaaa_001"
                proxy="localhost:3000/mobify/proxy/api"
                redirectURI="localhost:3000/callback"
                siteId="RefArch"
                shortCode="12345678"
                locale="en-US"
                currency="USD"
            >
                {children}
            </CommerceApiProvider>
        </QueryClientProvider>
    )
}

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. Commerce-sdk-react supports both the SLAS Public Client login flow and SLAS Private Client login flow. Authorization using a private client is supported in PWA Kit 3.5 and later, and is the recommended authorization workflow.

Using a private SLAS client

To enable a private client, see Use a SLAS Private Client.

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.

Example:

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>
}

Hooks

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:

use<ApiName>Mutation(EndpointName)

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 (
        <button
            onClick={() =>
                addItemToBasket.mutate({
                    parameters: {
                        basketId
                    },
                    body: {
                        productId: '25592770M',
                        price: 55,
                        quantity: 1
                    }
                })
            }
        />
    )
}
useCustomMutation

The useCustomMutation hook facilitates communication with the SCAPI custom endpoint. It has a different signature than the other declared mutation hooks.

Parameters
  • options (Object): Configuration for the API request.

    • method (String): The HTTP method to use (e.g., 'POST', 'GET').
    • customApiPathParameters (Object): Contains parameters to define the API path.
      • endpointPath (String): Specific endpoint path to target in the API.
      • apiName (String): The name of the API.
  • clientConfig (Object): Configuration settings for the client.

    • parameters (Object): Essential parameters required by the Salesforce Commerce Cloud API.
      • clientId (String): Your client ID.
      • siteId (String): Your site ID.
      • organizationId (String): Your organization ID.
      • shortCode (String): Short code for your organization.
    • proxy (String): Proxy address for API calls.
  • rawResponse (Boolean): Determines whether to receive the raw response from the API or a parsed version.

mutate Method

The mutation.mutate(args) function is used to execute the mutation. It accepts an argument args, which is an object that may contain the following properties:

  • headers (Object): Optional headers to send with the request.
  • parameters (Object): Optional query parameters to append to the API URL.
  • body (Object): Optional the payload for POST, PUT, PATCH methods.
Usage

Below is a sample usage of the useCustomMutation hook within a React component.

const clientConfig = {
    parameters: {
        clientId: 'CLIENT_ID',
        siteId: 'SITE_ID',
        organizationId: 'ORG_ID',
        shortCode: 'SHORT_CODE'
    },
    proxy: 'http://localhost:8888/mobify/proxy/api'
};

const mutation = useCustomMutation({
    options: {
        method: 'POST',
        customApiPathParameters: {
            endpointPath: 'test-hello-world',
            apiName: 'hello-world'
        }
    },
    clientConfig,
    rawResponse: false
});

// In your React component
<button onClick={() => mutation.mutate({
    body: { test: '123' },
    parameters: { additional: 'value' },
    headers: { ['X-Custom-Header']: 'test' }
})}>
    Send Request
</button>

It is a common scenario that a mutate function might pass a value along to a request that is dynamic and therefore can't be available when the hook is declared (contrary to example in Mutation Hooks above, which would work for a button that only adds one product to a basket, but doesn't handle a changeable input for adding a different product).

Sending a custom body param is supported, the example below combines this strategy with the use of a useCustomMutation() hook, making it possible to dynamically declare a body when calling a custom API endpoint.

import {useCustomMutation} from '@salesforce/commerce-sdk-react'
const clientConfig = {
    parameters: {
        clientId: 'CLIENT_ID',
        siteId: 'SITE_ID',
        organizationId: 'ORG_ID',
        shortCode: 'SHORT_CODE'
    },
    proxy: 'http://localhost:8888/mobify/proxy/api'
};

const mutation = useCustomMutation({
    options: {
        method: 'POST',
        customApiPathParameters: {
            endpointPath: 'path/to/resource',
            apiName: 'hello-world'
        }
    },
    clientConfig,
    rawResponse: false
});

// use it in a react component
const ExampleDynamicMutation = () => {
    const [colors, setColors] = useState(['blue', 'green', 'white'])
    const [selectedColor, setSelectedColor] = useState(colors[0])

    return (
        <>
            <select value={selectedColor} onChange={(e) => setSelectedColor(e.target.value)}>
                {colors.map((color, index) => (
                    <option key={index} value={color}>
                        {color}
                    </option>
                ))}
            </select>
            <button
                onClick={() =>
                    mutation.mutate({
                        parameters: {
                            myCustomParam: 'custom parameters'
                        },
                        body: {
                            resourceParam: selectedColor
                        }
                    })
                }
            />
        </>
    )
}

Mutations also have their named methods exported as constants, available in this way:

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).

Ultilities

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

useCommerceApi()

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()

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

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

useCustomerId()

useCustomerId() => null | string

useCustomerType()

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

useEncUserId()

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

useUsid()

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

Advanced: Customizing SDK Clients with transformSDKClient

To support advanced use cases, such as integrating with older templates or customizing API client behavior, commerce-sdk-react provides a utility called transformSDKClient. This utility wraps any Commerce SDK client instance in a JavaScript Proxy, enabling you to intercept and transform method arguments, headers, parameters, and other options before each SDK call is made.

This is especially useful for:

  • Adapting SDK clients for legacy or custom templates.
  • Removing references to unused SDK clients.

How It Works

transformSDKClient takes an SDK client instance and a configuration object. The configuration can include:

  • props: Arbitrary props you want to pass to your transformer.
  • transformer: A function that receives the props, method name, and options, and returns the transformed options.
  • onError: (Optional) A function to handle errors thrown by SDK methods.

Every method call on the proxied client passes through your transformer before being executed.

Example: Passing Custom SDK Clients to the Provider

You can use this utility to pass in your own SDK clients to the CommerceApiProvider via the apiClients prop, and apply custom transformations globally.

import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {ShopperProducts} from 'commerce-sdk-isomorphic'

// Create your SDK client instances as usual
const myShopperProductsClient = new ShopperProducts({
    // ...your config
})

// Pass your client(s) in the apiClients prop
const apiClients = {
    shopperProducts: myShopperProductsClient
    // ...add other clients as needed
}

const App = ({children}) => (
    <CommerceApiProvider
        // ...other required props
        apiClients={apiClients}
        // You can also pass custom headers, fetchOptions, etc.
    >
        {children}
    </CommerceApiProvider>
)

Note: The CommerceApiProvider will automatically wrap each client in apiClients with transformSDKClient, using a default transformer that injects headers and fetch options from the provider props. You must use props passed to CommerceApiProvider for setting custom headers and fetch options. transformSDKClient merges headers and options passed in as props with the default values.

API Reference

transformSDKClient<T>(
    client: T,
    config: {
        props?: any,
        transformer?: (props, methodName: string, options: any) => any,
        onError?: (methodName: string, error: any, options: any) => void
    }
): T
  • client: The SDK client instance to wrap.
  • config:
    • props: Any extra data you want to pass to your transformer.
    • transformer: Function to transform method arguments before each SDK call.
    • onError: (Optional) Function to handle errors from SDK methods.

Note: If you choose to pass the apiClients prop, you are responsible for providing all SDK clients you intend to use in your application. Any hooks or features that rely on a missing client will throw an error at runtime. This allows for customization, but requires you to explicitly include each client you need.

Handling Missing SDK Clients

With the introduction of the optional apiClients prop and support for custom SDK client injection, commerce-sdk-react now provides robust error handling for missing clients. If you attempt to use a query or mutation hook for a client that was not initialized or passed to the CommerceApiProvider, a clear error will be thrown.

For example, if you call a hook like useShopperProducts but did not provide a shopperProducts client in your apiClients prop, you will see an error message similar to this error.

Missing required client: shopperProducts. Please initialize shopperProducts class and provide it in CommerceApiProvider's apiClients prop.

This ensures that your application fails fast and provides actionable feedback, making it easier to debug configuration issues—especially when integrating with older templates or customizing your SDK client setup.

Disabling Automatic Auth Initialization

By default, CommerceApiProvider automatically initializes authentication by calling auth.ready() as soon as the provider renders. This is the standard and recommended behavior for most applications.

New in v3.4.0: You can now optionally disable this automatic initialization by passing the disableAuthInit prop:

<CommerceApiProvider
    // ...other required props
    disableAuthInit={true}
>
    {children}
</CommerceApiProvider>
  • Default: disableAuthInit is false (auth is initialized automatically).
  • When to use: Set disableAuthInit to true if you are initializing authentication outside of the provider (for example, in legacy PWA Kit templates or when using SSR with getProps). This prevents duplicate initialization and potential issues with tokens or customer information.

Note: For most modern PWA Kit and React Query-based apps, you do not need to set this prop.

Roadmap

  • Optimistic update support
  • SLAS private client support

Useful Links:

Readme

Keywords

none

Package Sidebar

Install

npm i @salesforce/commerce-sdk-react

Weekly Downloads

6,408

Version

3.4.0

License

See license in LICENSE

Unpacked Size

632 kB

Total Files

181

Last publish

Collaborators

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