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

# JavaScript Installation

> Install and configure DocSearch in vanilla JavaScript applications

DocSearch provides a standalone JavaScript package that works in any web application without requiring a framework. The package internally uses Preact for rendering while exposing a simple vanilla JS API.

## Installation

Install the `@docsearch/js` package using your preferred package manager:

<CodeGroup>
  ```bash npm theme={null}
  npm install @docsearch/js
  ```

  ```bash yarn theme={null}
  yarn add @docsearch/js
  ```

  ```bash pnpm theme={null}
  pnpm add @docsearch/js
  ```
</CodeGroup>

### CDN Installation

If you prefer not to use a package manager, you can load DocSearch directly from a CDN:

```html theme={null}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@4" />
<script src="https://cdn.jsdelivr.net/npm/@docsearch/js@4"></script>
```

## Basic Setup

<Steps>
  <Step title="Import DocSearch and styles">
    Import the `docsearch` function and CSS styles in your application:

    ```javascript theme={null}
    import docsearch from '@docsearch/js';
    import '@docsearch/css';
    ```
  </Step>

  <Step title="Add a container element">
    Add a container element to your HTML where DocSearch will be rendered. DocSearch generates a fully accessible search box for you, so use a container element (like a `div`), not an `input`:

    ```html theme={null}
    <div id="docsearch"></div>
    ```
  </Step>

  <Step title="Initialize DocSearch">
    Call the `docsearch()` function with your configuration. You can pass either a CSS selector string or an HTML element:

    ```javascript theme={null}
    const search = docsearch({
      container: '#docsearch',
      appId: 'YOUR_APP_ID',
      apiKey: 'YOUR_SEARCH_API_KEY',
      indexName: 'YOUR_INDEX_NAME',
    });
    ```
  </Step>
</Steps>

<Note>
  Don't have your Algolia credentials yet? [Apply to DocSearch](https://docsearch.algolia.com/apply) to get started for free.
</Note>

## Complete Example

Here's a complete working example:

```html index.html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DocSearch Example</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@4" />
</head>
<body>
  <div id="docsearch"></div>
  
  <script type="module">
    import docsearch from 'https://cdn.jsdelivr.net/npm/@docsearch/js@4/+esm';
    
    docsearch({
      container: '#docsearch',
      appId: 'YOUR_APP_ID',
      apiKey: 'YOUR_SEARCH_API_KEY',
      indexName: 'YOUR_INDEX_NAME',
    });
  </script>
</body>
</html>
```

## API Reference

### docsearch(props)

The main function that initializes DocSearch and returns a control instance.

#### Parameters

<ParamField path="container" type="string | HTMLElement" required>
  The container for your DocSearch component. Can be a CSS selector string or an HTMLElement.
</ParamField>

<ParamField path="appId" type="string" required>
  Your Algolia application ID.
</ParamField>

<ParamField path="apiKey" type="string" required>
  Your Algolia Search API key (public, search-only key).
</ParamField>

<ParamField path="indexName" type="string" required>
  The name of your Algolia index to search.
</ParamField>

<ParamField path="placeholder" type="string">
  Placeholder text for the search input. Defaults to "Search docs".
</ParamField>

<ParamField path="searchParameters" type="object">
  Additional Algolia search parameters to apply to all queries.

  ```javascript theme={null}
  searchParameters: {
    hitsPerPage: 10,
    facetFilters: ['version:1.0']
  }
  ```
</ParamField>

<ParamField path="transformItems" type="function">
  Hook to transform search results before rendering.

  ```javascript theme={null}
  transformItems: (items) => {
    return items.map(item => ({
      ...item,
      url: item.url.replace('https://example.com', '')
    }));
  }
  ```
</ParamField>

<ParamField path="hitComponent" type="function">
  Custom component to render individual search results. Supports JSX, HTML strings with the `html` helper, or function-based templates.

  ```javascript theme={null}
  hitComponent: ({ hit, children }, { html }) => {
    return html`<a href="${hit.url}" class="custom-hit">${children}</a>`;
  }
  ```
</ParamField>

<ParamField path="resultsFooterComponent" type="function">
  Custom component rendered at the bottom of the results panel.

  ```javascript theme={null}
  resultsFooterComponent: ({ state }, { html }) => {
    return html`<div class="footer">Showing ${state.collections.length} results</div>`;
  }
  ```
</ParamField>

<ParamField path="transformSearchClient" type="function">
  Hook to wrap or modify the Algolia search client.

  ```javascript theme={null}
  transformSearchClient: (searchClient) => {
    searchClient.addAlgoliaAgent('my-app', '1.0.0');
    return searchClient;
  }
  ```
</ParamField>

<ParamField path="maxResultsPerGroup" type="number">
  Maximum number of results to show per category. Defaults to 5.
</ParamField>

<ParamField path="disableUserPersonalization" type="boolean">
  Disable storage and display of recent and favorite searches. Defaults to `false`.
</ParamField>

<ParamField path="initialQuery" type="string">
  Query string to prefill when opening the search modal.
</ParamField>

#### Return Value

The `docsearch()` function returns a `DocSearchInstance` object with the following methods:

<ResponseField name="isReady" type="boolean" readonly>
  Returns `true` once the component is mounted and ready.
</ResponseField>

<ResponseField name="isOpen" type="boolean" readonly>
  Returns `true` if the modal is currently open.
</ResponseField>

<ResponseField name="open" type="function">
  Opens the search modal programmatically.
</ResponseField>

<ResponseField name="close" type="function">
  Closes the search modal programmatically.
</ResponseField>

<ResponseField name="openAskAi" type="function">
  Opens Ask AI mode in the modal.

  ```javascript theme={null}
  search.openAskAi({ query: 'How do I get started?' });
  ```
</ResponseField>

<ResponseField name="destroy" type="function">
  Unmounts the DocSearch component and cleans up resources.
</ResponseField>

## Programmatic Control

You can control DocSearch programmatically using the returned instance:

```javascript theme={null}
const search = docsearch({
  container: '#docsearch',
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'YOUR_INDEX_NAME',
  onReady: () => {
    console.log('DocSearch is ready!');
  },
  onOpen: () => {
    console.log('Search modal opened');
  },
  onClose: () => {
    console.log('Search modal closed');
  },
});

// Open the search modal programmatically
document.getElementById('custom-search-button').addEventListener('click', () => {
  search.open();
});

// Check if modal is open
console.log(search.isOpen); // true or false

// Open Ask AI with a pre-filled message
search.openAskAi({ query: 'How do I configure search?' });

// Clean up when done
search.destroy();
```

## Lifecycle Callbacks

DocSearch supports lifecycle callbacks to hook into important events:

```javascript theme={null}
docsearch({
  container: '#docsearch',
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'YOUR_INDEX_NAME',
  
  // Called when DocSearch is mounted and ready
  onReady: () => {
    console.log('DocSearch mounted');
  },
  
  // Called when the modal opens
  onOpen: () => {
    console.log('Modal opened');
  },
  
  // Called when the modal closes
  onClose: () => {
    console.log('Modal closed');
  },
});
```

## Styling

DocSearch comes with default styles via `@docsearch/css`. You can customize the appearance by:

1. **CSS Variables**: Override DocSearch's CSS custom properties
2. **Custom Classes**: Target DocSearch's class names with your own CSS
3. **Theme Object**: Pass a theme configuration (see React documentation)

```css theme={null}
:root {
  --docsearch-primary-color: #5468ff;
  --docsearch-text-color: #1c1e21;
  --docsearch-spacing: 12px;
  --docsearch-icon-stroke-width: 1.4;
  --docsearch-highlight-color: var(--docsearch-primary-color);
  --docsearch-muted-color: #969faf;
  --docsearch-container-background: rgba(101, 108, 133, 0.8);
  --docsearch-modal-background: #f5f6f7;
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Configuration" icon="gear" href="/api/configuration">
    Learn about all available configuration options
  </Card>

  <Card title="Styling" icon="palette" href="/concepts/styling">
    Customize the appearance of your search
  </Card>

  <Card title="Ask AI" icon="sparkles" href="/concepts/ask-ai">
    Enable AI-powered search assistance
  </Card>

  <Card title="API Reference" icon="code" href="/api/docsearch-js">
    Explore the complete API documentation
  </Card>
</CardGroup>
