Skip to main content

Integrate Kapa into Algolia search bar

Some of our customers use Algolia's search for their documentation. Traditional search is useful in various scenarios but more often users will get better answers from Kapa's "Ask AI". A common ask from our customers is to always show Kapa as the top result in the Algolia search bar.

Algolia search bar with Kapa

This approach has two main benefits:

  • Users can quickly ask Kapa if their search results are not satisfactory.
  • It gives Kapa further visibility and drives adoption.

This tutorial implements this pattern with a React example. You can find the full implementation in this sandbox.

Implementation

Step 1: Install the website widget

Add the website widget script to your index.html file (or the equivalent file for your platform). Check out the detailed installation instructions for help with this step.

This script initializes the website widget in your website so we can later open it programmatically from the search bar using the open function.

<script
async
src="https://widget.kapa.ai/kapa-widget.bundle.js"
data-website-id="6d04c434-4090-4ebf-aeb3-8e90645a504d"
data-project-name="kapa.ai"
data-project-color="#5B4CFE"
data-project-logo="https://avatars.githubusercontent.com/u/122976076?s=200&amp;v=4"
data-modal-disclaimer="This is a [Kapa-powered](kapa.ai) **AI assistant**."
data-search-mode-enabled="true"
data-modal-title="kapa.ai - Ask AI Website Widget"
data-button-hide="true"
></script>

We create a custom buttom and integrate it with Algolia's InstantSearch component. We always show this button above the Algolia search results. We use the useInstantSearch hook to retrieve the user’s current search query from Algolia’s state. The “Ask AI” button will dynamically appear whenever a search query is active, offering users an additional way to engage with Kapa.

When clicked, it calls the window.Kapa.open() function, opening the Kapa modal with the query pre-filled. The submit: true option ensures the query is submitted automatically when the modal opens.

function Hit({ hit }) {
return (
<>
<Highlight hit={hit} attribute="name" className="Hit-label" />
<span className="Hit-price">${hit.price}</span>
</>
);
}

function AskAIButton() {
const { uiState } = useInstantSearch();

const { query } = uiState["instant_search"];

const handleClick = () => {
window.Kapa.open({ query, submit: true });
};

return query ? (
<button className="ask-ai" onClick={handleClick}>
<span className="ais-Highlight Hit-label">
<span className="ais-Highlight-nonHighlighted">
Ask AI about "{query}"
</span>
</span>
</button>
) : null;
}

export function App() {
return (
<InstantSearch
searchClient={searchClient}
indexName="instant_search"
routing={true}
insights={true}
>
<div className="Container">
<div className="Search">
<SearchBox placeholder="Search" autoFocus />
<div className="Search-header">
<PoweredBy />
</div>
<AskAIButton />
<Hits hitComponent={Hit} />
</div>
</div>
</InstantSearch>
);
}