> ## Documentation Index
> Fetch the complete documentation index at: https://www.algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PWA Kit demo and starter code

> Learn how to integrate Algolia into your Progressive Web App Kit project.

The Algolia PWA Kit demo shows how to add Autocomplete, InstantSearch, and Recommend to a [Salesforce B2C Commerce PWA Kit](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/pwa-kit-overview.html) storefront.
Use the starter code to integrate these features into your own project.

> [card] [View Algolia PWA Kit demo](https://algolia-pwa-demo-production.mobify-storefront.com)
>
> Try the storefront demo with Autocomplete, InstantSearch, and Recommend.

> [card] [Explore starter code](https://github.com/algolia/algolia-pwa-demo)
>
> Browse the PWA Kit starter code and integration source on GitHub.

## Integration with PWA Kit

The demo uses PWA Kit template extensibility with `@salesforce/retail-react-app` as its base template.
It includes only files that differ from the base template.
Copy the changes you need into your project or
use the demo repository as starter code.

For more information,
see [Template extensibility](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/template-extensibility.html).

## Before you begin

This guide requires:

* Algolia Search & Discovery cartridge version 25.3.0 or later.
* Salesforce's [`storefrontdata`](https://github.com/SalesforceCommerceCloud/storefrontdata) sample data.
  The `storefrontdata` repository requires [authenticated access](https://trailhead.salesforce.com/content/learn/modules/b2c-developer-resources-and-tools/b2c-developer-access-repositories).
* The default [Variation product](https://www.algolia.com/doc/integration/salesforce-commerce-cloud-b2c/indexing/product-indexing/indexing-attributes.md#variation-product-record-example) record model.
* [Node.js version 18 or later](https://nodejs.org/en/download/package-manager).
* [npm 9 or later](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
* If you intend to use Recommend components that require a trained model, [train the corresponding model](https://www.algolia.com/doc/guides/algolia-recommend/how-to/set-up.md#train-the-recommend-models).

## Installation

This guide covers `@salesforce/retail-react-app` version 4.0.0.
For other versions,
check the [PWA Kit release notes](https://github.com/SalesforceCommerceCloud/pwa-kit/releases) for configuration differences.

### Run the Algolia demo application

1. [Set up API access](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/setting-up-api-access.html) to your Salesforce B2C Commerce instance.

2. In Salesforce Business Manager, go to **Merchant Tools > Algolia > Algolia**.
   In **Additional Product Attributes**, enter `color`, `size`, `colorVariations`, `masterID`, `lsImage`, `short_description`, `long_description`, `pricebooks`, `brand`, `name`, and `in_stock`.

   These attributes determine which additional product fields the cartridge sends to Algolia. For more information, see [Custom preferences](https://www.algolia.com/doc/integration/salesforce-commerce-cloud-b2c/getting-started/custom-preferences.md).
   If you're using other datasets or a custom indexing approach, adjust the attribute list for your implementation.

3. [Index your products and content](https://www.algolia.com/doc/integration/salesforce-commerce-cloud-b2c/indexing/product-indexing/overview) from your Salesforce B2C Commerce instance into Algolia.

4. Configure your indices in the Algolia dashboard:

   * [Create a Query Suggestions index](https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/query-suggestions/js.md#set-up-query-suggestions).
   * [Configure facets](https://www.algolia.com/doc/integration/salesforce-commerce-cloud-b2c/getting-started/configure-your-search.md#configure-your-facets) for categories, brands, colors, and sizes for the primary product index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.).
   * [Create replicas](https://www.algolia.com/doc/integration/salesforce-commerce-cloud-b2c/getting-started/configure-your-search.md#configure-your-replicas) for sorting options.
   * [Create a rule](https://www.algolia.com/doc/guides/managing-results/rules/rules-overview) for the primary product index to enable the rendering of product previews in the autocomplete section.

5. Import the following rule configuration using **Enhanced > Rules > Import/Export**.

   ```json JSON expandable icon=braces theme={"system"}
   {
     "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"
   }
   ```

6. Clone the Algolia PWA Kit demo repository from GitHub and go to the cloned repository:

   ```sh Command line icon=square-terminal theme={"system"}
   git clone https://github.com/algolia/algolia-pwa-demo.git
   ```

   ```sh Command line icon=square-terminal theme={"system"}
   cd algolia-pwa-demo
   ```

7. Install the dependencies:

   ```sh Command line icon=square-terminal theme={"system"}
   npm install
   ```

8. Copy the [example file](https://github.com/algolia/algolia-pwa-demo/blob/master/config/algolia-config.example.json) to `config/algolia-config.json`.
   Update the Algolia credentials and index names.

9. Copy the [example file](https://github.com/algolia/algolia-pwa-demo/blob/master/config/commerce-api-config.example.json) to `config/commerce-api-config.json`.
   Update the Salesforce B2C Commerce API credentials.

10. Set the `PWA_KIT_SLAS_CLIENT_SECRET` in your environment variables.

    To learn more about creating [Shopper Login and API Access Service (SLAS)](https://developer.salesforce.com/docs/commerce/commerce-api/guide/slas.html)
    credentials, see [Build Your Site](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/build-customize.html) in the PWA Kit documentation.

11. Start the development server:

    ```sh Command line icon=square-terminal theme={"system"}
    npm run start
    ```

The demo runs at `localhost:3000` using the credentials and index names in `config/algolia-config.json`.

### Integrate Algolia into your existing PWA Kit project

1. Index your products using the Algolia indexing jobs in Salesforce B2C Commerce.

2. Create an `algolia-config.json` file in your root folder or use and rename the [example file.](https://github.com/algolia/algolia-pwa-demo/blob/master/config/algolia-config.example.json)

3. Adjust your Commerce API and PWA Kit configuration as needed.

   For more information, see [Configuration files](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/configuration-options.html).

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

   ```sh Command line icon=square-terminal theme={"system"}
   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`](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/components/algolia) directory from the demo repository to your project.

6. Update your [`overrides/app/routes.jsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/routes.jsx) file to include the Algolia product list and detail pages:

   ```jsx JavaScript icon=code expandable theme={"system"}
   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,
     },
     // ...
   ];
   ```

   If you don't need recommendation widgets on product detail pages,
   omit the `ProductDetail` route override.

### `algolia-config.json` file

The following JavaScript excerpt shows the Algolia configuration structure.
For the complete JSON file,
see [`algolia-config.example.json`](https://github.com/algolia/algolia-pwa-demo/blob/master/config/algolia-config.example.json).

```js JavaScript icon=code expandable theme={"system"}
algolia: {
  appId: 'ALGOLIA_APPLICATION_ID',
  apiKey: 'ALGOLIA_SEARCH_API_KEY',
  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](https://dashboard.algolia.com/account/api-keys/all)
* `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 index containing FAQ records. The demo uses the content index. To search a separate FAQ index, update this value.
* `indices.categories`: the categories index name

## InstantSearch implementation

The Algolia PWA Kit 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:

* [`react-instantsearch`](https://www.npmjs.com/package/react-instantsearch)
* [`algoliasearch`](https://www.npmjs.com/package/algoliasearch)

InstantSearch in the demo provides the following features:

* Search results
* Category listings
* Filters for category, color, size, price, and brand
* Pagination
* Sorting by relevance or price
* Content search in a separate tab
* Color swatches on product listings

To customize filtering, change the hardcoded `hierarchicalCategoryAttributes` and
`filterEls` variables in the [`index.jsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/pages/algolia-product-list/index.jsx) file.
For example,
to filter by `collection` instead of `brand`,
set the `AlgoliaCheckboxRefinements` component's `attribute` prop to `"collection"`:

```jsx JavaScript icon=code expandable theme={"system"}
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>
  </>
);
```

To add a filter for `material`,
add an `AlgoliaCheckboxRefinements` component to `filterEls` with `attribute="material"`:

```jsx JavaScript icon=code expandable theme={"system"}
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 implementation details, see the [product listing page](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/pages/algolia-product-list/index.jsx) and
  its [partial components](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/pages/algolia-product-list/partials).
* For library documentation,
  see [React InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react.md).

## Autocomplete implementation

The demo replaces the default search box with the [Autocomplete widget](https://www.algolia.com/doc/ui-libraries/autocomplete/introduction/what-is-autocomplete.md).
The Autocomplete component is in the [`overrides/app/components/algolia/autocomplete`](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/components/algolia/autocomplete) directory.
The implementation in [`index.jsx`](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/components/algolia/autocomplete/index.jsx) and
uses the following [plugins](https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/plugins.md).

### `recentSearchesPlugin`

Displays users' recent searches with the [`createLocalStorageRecentSearchesPlugin`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createLocalStorageRecentSearchesPlugin).
The plugin stores recent searches in the browser's local storage under the `pwa-recent-searches` key.

### `querySuggestionsPlugin`

Provides Query Suggestions based on the user's input.
It uses the [`createQuerySuggestionsPlugin`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-query-suggestions/createQuerySuggestionsPlugin) and fetches suggestions from the `indices.querySuggestions` index in the configuration.

### `categoriesPlugin`

Fetches and displays category suggestions.
It uses the [`getAlgoliaResults`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/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`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/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 index specified by `indices.faq` using the [`getAlgoliaResults`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/getAlgoliaResults) function.

### `popularPlugin`

Displays popular searches based on Algolia's Query Suggestions feature.
It uses the [`createQuerySuggestionsPlugin`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-query-suggestions/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`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/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`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/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.
Replace the hardcoded category images in [`popularCategoriesPlugin.tsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/components/algolia/autocomplete/plugins/popularCategoriesPlugin.tsx).

The `quickAccessPlugin` displays content configured through [Algolia Rules](https://www.algolia.com/doc/guides/managing-results/rules/rules-overview).
Customize the configuration in [`quickAccessPlugin.tsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/components/algolia/autocomplete/plugins/quickAccessPlugin.tsx).

For demonstration purposes, the [`index.jsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/components/algolia/autocomplete/index.jsx) file includes sample data.
Customize the Algolia component styles in [`style.css`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/components/algolia/style.css).

## Recommend implementation

The demo includes [Algolia Recommend](https://www.algolia.com/doc/guides/algolia-recommend/overview) components for product recommendations.
These components are in [`overrides/app/components/algolia/recommend`](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/components/algolia/recommend).

The available Recommend components are:

* Frequently bought together: displays products frequently bought with the current product
* Looking similar: shows products that look like the current product
* Related products: displays products with similar attributes as the current product
* Trending items: displays trending items, based on a specific facet name and facet values
* Trending facets: shows trending facet values for a facet name

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

The following are examples of the Recommend components.
Import them from the [`overrides/app/components/algolia/recommend`](https://github.com/algolia/algolia-pwa-demo/tree/master/overrides/app/components/algolia/recommend) directory for use anywhere in your project.

* Frequently bought together:

  ```jsx JavaScript icon=code theme={"system"}
  <FrequentlyBoughtTogether product={currentProduct} />;
  ```

* Looking similar:

  ```jsx JavaScript icon=code theme={"system"}
  <LookingSimilar product={currentProduct} />;
  ```

* RelatedProducts:

  ```jsx JavaScript icon=code theme={"system"}
  <RelatedProducts product={currentProduct} />;
  ```

* TrendingItems:

  ```jsx JavaScript icon=code theme={"system"}
  <TrendingItems facetName="brand" facetValue="Example Brand" />;
  ```

* TrendingFacets:

  ```jsx JavaScript icon=code theme={"system"}
  <TrendingFacets facetName="category" />;
  ```

For examples of how to use these components, see the [`index.jsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/pages/algolia-product-detail/index.jsx) file.

In the preceding examples:

* `product` represents the current product object for displaying recommendations.
  It matches the [`context-object`](https://help.salesforce.com/s/articleView?id=cc.b2c_einstein_validator_responses.htm\&type=5) in Einstein Recommendation [`isslots`](https://developer.salesforce.com/docs/commerce/b2c-commerce/guide/b2c-isslot.html).
* `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`](https://github.com/algolia/algolia-pwa-demo/tree/master/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.

## Next steps

Customize the starter code for your storefront:

* Integrate [conversion events](https://www.algolia.com/doc/guides/building-search-ui/events/react.md)
* Customize the image logic in [`popularCategoriesPlugin.tsx`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/components/algolia/autocomplete/plugins/popularCategoriesPlugin.tsx)
* Add localization and multi-site support
* Adjust the FAQ plugin configuration to use a specific index

## Common issues

| Problem | Solution |
| - | - |
| Index not found | Create the index and set its name in [`algolia-config.json`](https://github.com/algolia/algolia-pwa-demo/blob/master/config/algolia-config.example.json) |
| Recommend model not found | [Train the model for the corresponding index](https://www.algolia.com/doc/guides/algolia-recommend/overview) |
| Query Suggestions index not found | [Create a Query Suggestions index](https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/query-suggestions/js.md#set-up-query-suggestions) and point to it in `algolia-config.json` |
| Product preview section doesn't work | [Create a rule with the appropriate data](#run-the-algolia-demo-application) |
| Broken page when clicking a product tile | In [`modelHelper.js`](https://github.com/algolia/algoliasearch-sfcc-b2c/blob/master/cartridges/int_algolia/cartridge/scripts/algolia/helper/modelHelper.js), set `isPWA` to `true` |
| Broken color codes | Add or correct the color codes in `cssColorGroups` in [`overrides/app/constants.js`](https://github.com/algolia/algolia-pwa-demo/blob/master/overrides/app/constants.js) |
