Integrations / Salesforce Commerce Cloud B2C

PWA Kit demo and starter code

The PWA demo showcases Algolia’s search and discovery features using the Salesforce Commerce Cloud PWA Kit. This starter code helps you incorporate Algolia into your PWA Kit project. It uses the following Algolia features:

  • Autocomplete for intelligent query suggestions and previews
  • InstantSearch for product listings and search results
  • Recommend for product recommendations

Integration with Salesforce Commerce Cloud PWA Kit

The Algolia PWA Demo uses the template extensibility feature of the official Salesforce PWA Kit. This approach lets you use the @salesforce/retail-react-app repository as a base template and include only the overridden or customized files from the original template.

You can selectively incorporate the relevant files or changes into your repositories or use the entire demo repository as starter code for your project.

For more information about template extensibility in the Salesforce PWA Kit, refer to the Salesforce documentation.

Before you begin

This guide requires Node.js version 18 or later, npm 9 or later, and an Algolia account .

Installation

This guide covers @salesforce/retail-react-app version 3.0.1. If you use a different version, some configurations may differ. Check the changelog for your specific version to see any relevant changes.

Run the Algolia demo application

  1. Setup your API access to Salesforce Commerce Cloud.

  2. Index your products and content from your Salesforce Commerce Cloud instance into Algolia.

    The demo assumes you’re using:

    • Salesforce’s storefront data, sample catalog, and content library
    • Algolia’s cartridge for product indexing.
    • Using the default variant-level model
    • Specify color, size, colorVariations, masterID, lsImage, short_description, long_description, pricebooks, brand, name, in_stock as Additional Product Attributes in the custom preferences. If you’re using other datasets or a custom indexing approach, adjust your implementation accordingly.
  3. Configure your indices in the Algolia Dashboard:

    To import the following pre-configuration JSON, click the Enhanced > Rules > Import/Export icon.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    
       {
         "conditions": [{
           "anchoring": "is",
           "pattern": "",
           "alternatives": false,
           "context": "quickAccess"
         }],
         "consequence": {
           "userData": {
             "items": [{
                 "href": "/category/womens-outfits",
                 "image": "https://res.cloudinary.com/hilnmyskv/image/upload/v1645453369/sales_banner_y1hsr8.jpg",
                 "subtitle": "Women",
                 "template": "sales-banner",
                 "title": "Outfits"
               },
               {
                 "date": "Till March 25th",
                 "href": "/category/womens",
                 "image": "https://res.cloudinary.com/hilnmyskv/image/upload/v1645453422/sales_code_vuatep.jpg",
                 "subtitle": "with the code CODE_ALGOLIA",
                 "template": "sales-code",
                 "title": "Sale on Women Top"
               },
               {
                 "href": "/category/top-seller",
                 "image": "https://res.cloudinary.com/hilnmyskv/image/upload/v1645453466/new_collection_nloeb6.jpg",
                 "subtitle": "spring / summer 2024",
                 "template": "new-collection",
                 "title": "Top sellers"
               },
               {
                 "href": "/category/womens-jewelry",
                 "links": [{
                     "href": "/category/womens-jewelry",
                     "text": "Track my order"
                   },
                   {
                     "href": "/category/womens-jewelry",
                     "text": "Delivery & Returns"
                   },
                   {
                     "href": "/category/womens-jewelry",
                     "text": "FAQ"
                   }
                 ],
                 "template": "help",
                 "title": "how can we help?"
               }
             ]
           },
           "filterPromotes": true
         },
         "enabled": true,
         "description": "Autocomplete quick access on empty query state",
       }
    
  4. Clone the Algolia PWA Demo repository from GitHub and go to the cloned repository:

    1
    
     git clone https://github.com/algolia/algolia-pwa-demo.git
    

    1
    
     cd algolia-pwa-demo
    

  5. Install the dependencies:

    1
    
    npm install
    
  6. Create an algolia-config.json file in your config folder or use and rename the example file, then update the Algolia app credentials and indices in it.

  7. Create a commerce-api-config.json file in your config folder or use and rename the example file, then update the Salesforce Commerce Cloud API credentials in it.

  8. Set the PWA_KIT_SLAS_CLIENT_SECRET in your environment variables.

You can find instructions on how to create Shopper Login and API Access Service (SLAS) credentials and get the necessary Salesforce Commerce Cloud API credentials in the PWA-Kit documentation.

  1. Start the development server:

    1
    
    npm run start
    

The demo runs on localhost:3000 using the default Algolia app credentials in the algolia-config.json file.

Integrate Algolia into your existing PWA Kit project

  1. Create your Algolia indices using SFCC Jobs.

  2. Create an algolia-config.json file in your root folder or use and rename the example file.

  3. Adjust your Commerce API and PWA Kit configuration as needed. Refer to the Salesforce documentation for more information.

  4. Install the necessary dependencies to use Algolia styles in your PWA application:

    1
    
     npm install autoprefixer css-loader postcss-loader style-loader --save-dev
    

    Copy the babel.config.js and postcss.config.js files from the demo repository to your project’s root directory.

  5. Copy the overrides/app/components/algolia directory from the demo repository to your project.

  6. Update your overrides/app/route.jsx file to include the Algolia product list and detail pages:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
     const ProductList = loadable(() => import('./pages/algolia-product-list'), {
       fallback
     })
    
     const ProductDetail = loadable(() => import('./pages/algolia-product-detail'), {
       fallback
     })
    
     const routes = [
       // ...
       {
         path: '/search',
         component: ProductList
       },
       {
         path: '/category/:categoryId',
         component: ProductList
       },
       {
         path: '/product/:productId',
         component: ProductDetail
       },
       // ...
     ]
    

    The productDetail page now showcases recommendation widgets. If the recommendation widgets on the product detail page aren’t required, you can remove the ProductDetail component as necessary.

algolia-config.json file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
algolia: {
  appId: 'xxx',
  apiKey: 'xxx',
  indices: {
    querySuggestions: 'pwa__products__en_GB_query_suggestions',
    contents: 'pwa__contents__en_GB',
    faq: 'pwa__contents__en_GB',
    categories: 'pwa__categories__en_GB',
    primary: {
      label: 'Sort By: Best Matches',
      value: 'pwa__products__en_GB'
    },
    replicas: [
      {
        label: 'Sort By: Price Low to High',
        value: 'pwa__products__en_GB_price_asc'
      },
      {
        label: 'Sort By: Price High to Low',
        value: 'pwa__products__en_GB_price_desc'
      }
    ]
  }
},
  • appId: your Algolia application ID, which you can find in the Algolia dashboard
  • apiKey: your Algolia API key, which you can find in the Algolia dashboard
  • indices.querySuggestions: the Query Suggestions index name
  • indices.primary.label: the label for the default sorting option
  • indices.primary.value: the primary product index name
  • indices.replicas: a sorting options array and their corresponding index names
  • indices.contents: the content index name
  • indices.faq: the FAQ index name. You can use a specific index; the content index serves demonstration purposes.
  • indices.categories: the categories index name.

InstantSearch implementation

The Algolia PWA demo uses the algolia-product-list page for the /search and /category/:categoryId routes. It uses the following npm packages for building the InstantSearch experience:

InstantSearch in the demo provides the following features:

  • Search
  • Listing category pages
  • Filtering on category, color, size, price, and brand
  • Pagination
  • Three different sorting strategies: best match, price low to high, price high to low
  • Content search results with a secondary search tab
  • Color swatches, which lets users see all the color alternatives on the product listing page.

To customize filtering, change the hardcoded hierarchicalCategoryAttributes, and filterEls variables in the overrides/app/pages/algolia-product-list/index.jsx file. For example, to use a different refinement like “collection” instead of “brand”, update the AlgoliaCheckboxRefinements attributes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    const filterEls = (
        <>
            <Accordion allowMultiple>
                <AlgoliaHierarchicalRefinements
                    attributes={hierarchicalCategoryAttributes}
                    title="Category"
                />
                <AlgoliaColorRefinements attribute="color" title="Color" />
                <AlgoliaCheckboxRefinements attribute="size" title="Size" />
                <AlgoliaRangeRefinements attribute="price.USD" title="Price" />
                <AlgoliaCheckboxRefinements attribute="collection" title="Collections" />
            </Accordion>
        </>
    )

Or if you want to add a new facet like “material”, add a new AlgoliaCheckboxRefinements component with necessary attributes in the filterEls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    const filterEls = (
        <>
            <Accordion allowMultiple>
                <AlgoliaHierarchicalRefinements
                    attributes={hierarchicalCategoryAttributes}
                    title="Category"
                />
                <AlgoliaColorRefinements attribute="color" title="Color" />
                <AlgoliaCheckboxRefinements attribute="size" title="Size" />
                <AlgoliaRangeRefinements attribute="price.USD" title="Price" />
                <AlgoliaCheckboxRefinements attribute="brand" title="Brand" />
                <AlgoliaCheckboxRefinements attribute="material" title="Material" />
            </Accordion>
        </>
    )

For a detailed understanding of the InstantSearch implementation, refer to the overrides/app/pages/algolia-product-list/index.jsx file and the components inside the overrides/app/pages/algolia-product-list/partials directory, as well as the complete InstantSearch documentation.

Autocomplete implementation

The Algolia PWA Demo overrides the default search bar with Algolia’s Autocomplete widget. The Autocomplete component resides in the overrides/app/components/algolia/autocomplete directory. The main file for the Autocomplete implementation is overrides/app/components/algolia/autocomplete/index.jsx. It imports various plugins and components to create a feature-rich autocomplete experience.

The Autocomplete component uses the following plugins:

recentSearchesPlugin

Displays recent searches for each customer. It uses the createLocalStorageRecentSearchesPlugin. The plugin stores recent searches in the browser’s local storage under the key ‘pwa-recent-searches’.

querySuggestionsPlugin

Provides query suggestions based on the user’s input. It uses the createQuerySuggestionsPlugin and fetches suggestions from the indices.querySuggestions index in the configuration.

categoriesPlugin

Fetches and displays category suggestions. It uses the getAlgoliaResults function to retrieve category results from the indices.categories index in the configuration.

brandsPlugin

Displays popular brands based on Algolia’s Trending Facets feature. It uses the getAlgoliaFacets function to fetch trending brands from the indices.primary.value index in the configuration.

faqPlugin

Provides FAQ suggestions based on the user’s input. It fetches results from the algolia.indices.faq index using the getAlgoliaResults function.

popularPlugin

Displays popular searches based on Algolia’s Query Suggestions feature. It uses the createQuerySuggestionsPlugin to retrieve popular searches from the indices.querySuggestions index in the configuration.

popularCategoriesPlugin

Fetches and displays popular categories based on Algolia’s facet values. It uses the getAlgoliaFacets function to retrieve popular categories from the indices.primary.value index in the configuration.

productPlugin

Fetches and displays product suggestions based on the user’s input. It uses the getAlgoliaResults function to retrieve product results from the indices.primary.value index in the configuration.

Customization and extensibility

The popularCategoriesPlugin helps display popular product categories based on search results. It uses hardcoded images. Change them in the file popularCategoriesPlugin.tsx.

The QuickAccessPlugin showcases Rules and always returns the same result that depends on the rule configuration. The overrides/app/components/algolia/autocomplete/plugins/quickAccessPlugin.tsx file includes an example configuration.

The RecentSearchesPlugin uses local storage for each user. For demonstration purposes, the overrides/app/components/algolia/autocomplete/index.jsx file includes sample data. The overrides/app/components/algolia/style.css file includes all the styles for Algolia components. You can customize the styles according to your design requirements.

These plugins work together to provide a comprehensive autocomplete experience, offering suggestions for recent searches, query suggestions, categories, brands, FAQs, popular searches, popular categories, and products.

Recommend implementation

The Algolia PWA Demo includes several Recommend components to showcase how to add personalized product recommendations to your PWA Kit project. These components are in the overrides/app/components/algolia/recommend directory.

The available Recommend components are:

  • FrequentlyBoughtTogether: displays products frequently bought with the current product
  • LookingSimilar: shows products that look like the current product
  • RelatedProducts: displays products with similar attributes as the current product
  • TrendingItems: displays trending products (based on a specific facet name and facet values).
  • TrendingFacets: shows trending facet values for a facet name.

Each Recommend component uses the @algolia/recommend-react package to fetch recommendations from Algolia.

The following are examples of the Recommend components. Import them from the overrides/app/components/algolia/recommend directory for use anywhere in your project.

FrequentlyBoughtTogether:

1
<FrequentlyBoughtTogether product={currentProduct} />

LookingSimilar:

1
<LookingSimilar product={currentProduct} />

RelatedProducts:

1
<RelatedProducts product={currentProduct} />

TrendingItems:

1
2
3
4
<TrendingItems
  facetName="brand"
  facetValue="Example Brand"
/>

TrendingFacets:

1
<TrendingFacets facetName="category" />

Find examples of how to use the FrequentlyBoughtTogether, RelatedProducts, and LookingSimilar components in the overrides/app/pages/algolia-product-detail/index.jsx file.

In the preceding examples:

  • product represents the current product object for displaying recommendations. It’s like the context-object in Einstein Recommendation isslots.
  • facetName and facetValue specify the facet name and value for fetching trending items.

The Recommend components also include extra props for customization, such as:

  • recommendClient to specify the Algolia Recommend client
  • indexName to specify the index to fetch recommendations from
  • headerComponent and itemComponent for rendering custom headers and items.

To use the Recommend components in your PWA Kit project:

  1. Import the desired Recommend component from the overrides/app/components/algolia/recommend directory.

  2. Configure the necessary props, such as the current product, click event handlers, and any extra customization options.

  3. Place the Recommend component in the appropriate location within your product detail page or any other relevant page.

  4. Ensure you have trained recommendation models in your Algolia account.

Next steps

Some parts of the starter code are solely for demonstration purposes. Extend, customize, or remove parts of the implementation according to your needs. Here are some areas to consider:

Troubleshooting common issues

Problem Solution
Index not found Check if you have created the index and pointed to it in the algolia-config.json file.
Recommend model not found Train the model for the corresponding index
Query Suggestions not found Create a Query Suggestions index and point to it in the algolia-config.json file
Quick View section doesn’t work Create a rule with the appropriate data
Broken page when clicking a product tile Set the isPWA hardcoded variable to true in the modelHelper.js file.
Broken color codes Update or add missing color codes in cssColorGroups in the overrides/app/constants.js file
Did you find this page helpful?