Skip to main content
The docsearch() function is the main entry point for integrating DocSearch into vanilla JavaScript applications. It mounts a DocSearch component to a DOM element and returns an instance for programmatic control.

Function Signature

function docsearch(props: DocSearchProps): DocSearchInstance

Parameters

The docsearch() function accepts a single DocSearchProps object with the following properties:

Core Configuration

container
string | HTMLElement
required
The DOM element or CSS selector where DocSearch will be mounted.
container: '#docsearch'
// or
container: document.getElementById('docsearch')
appId
string
required
Your Algolia application ID.
apiKey
string
required
Public API key with search permissions for your index.
indexName
string
Name of the Algolia index to query.
Deprecated: Use indices property instead. Will be removed in a future version.
indices
Array<DocSearchIndex | string>
List of indices and optional search parameters to be used for search.
indices: [
  'my-index',
  {
    name: 'blog-index',
    searchParameters: { facetFilters: ['type:blog'] }
  }
]

Search Customization

searchParameters
SearchParamsObject
Additional Algolia search parameters to merge into each query.
Deprecated: Use indices property instead. Will be removed in a future version.
placeholder
string
Placeholder text for the search input.
maxResultsPerGroup
number
Maximum number of hits to display per source/group.
initialQuery
string
Query string to prefill when opening the modal.
disableUserPersonalization
boolean
Disable storage and usage of recent and favorite searches.
recentSearchesLimit
number
default:7
Maximum number of recent searches to save and display.
recentSearchesWithFavoritesLimit
number
default:4
Maximum number of recent searches to display when there are favorited searches.

Ask AI Configuration

askAi
DocSearchAskAi | string
Configuration for Ask AI mode. Pass a string assistant ID or a full config object.
askAi: 'your-assistant-id'
// or
askAi: {
  assistantId: 'your-assistant-id',
  indexName: 'ai-index',
  apiKey: 'ai-api-key',
  appId: 'ai-app-id',
  suggestedQuestions: true,
  searchParameters: {
    facetFilters: ['type:docs']
  }
}

Customization Functions

transformItems
(items: DocSearchHit[]) => DocSearchHit[]
Hook to post-process hits before rendering.
transformItems: (items) => {
  return items.map(item => ({
    ...item,
    content: item.content?.toUpperCase()
  }));
}
hitComponent
function
Custom component to render an individual hit. Supports multiple template patterns:
// HTML template with html helper
hitComponent({ hit, children }, { html }) {
  return html`<div class="custom-hit">${children}</div>`;
}

// JSX-like template
hitComponent({ hit, children }) {
  return <div className="custom-hit">{children}</div>;
}
Parameters:
  • props.hit: The search hit object
  • props.children: Default hit rendering
  • helpers.html: HTML template helper
Custom component rendered at the bottom of the results panel.
resultsFooterComponent({ state }, { html }) {
  return html`<div>Total results: ${state.collections.length}</div>`;
}
Parameters:
  • props.state: Autocomplete state object
  • helpers.html: HTML template helper
transformSearchClient
(searchClient: DocSearchTransformClient) => DocSearchTransformClient
Hook to wrap or modify the Algolia search client.
transformSearchClient: (searchClient) => {
  searchClient.addAlgoliaAgent('my-app', '1.0.0');
  return searchClient;
}
getMissingResultsUrl
({ query }: { query: string }) => string
Builds a URL to report missing results for a given query.
getMissingResultsUrl: ({ query }) => {
  return `https://github.com/myorg/docs/issues/new?title=Missing: ${query}`;
}
navigator
AutocompleteNavigator
Custom navigator for controlling link navigation. Useful for client-side routing.
navigator: {
  navigate({ itemUrl }) {
    router.push(itemUrl);
  }
}

Styling and Theming

theme
DocSearchTheme
Theme overrides applied to the modal and related components.
theme: {
  primaryColor: '#5468ff',
  backgroundColor: '#ffffff'
}
translations
DocSearchTranslations
Localized strings for the button and modal UI.
translations: {
  button: {
    buttonText: 'Search',
    buttonAriaLabel: 'Search'
  },
  modal: {
    searchBox: {
      resetButtonTitle: 'Clear',
      cancelButtonText: 'Cancel'
    }
  }
}

Lifecycle Callbacks

onReady
() => void
Called once DocSearch is mounted and ready for interaction.
onOpen
() => void
Called when the modal opens.
onClose
() => void
Called when the modal closes.
interceptAskAiEvent
(initialMessage: InitialAskAiMessage) => boolean | void
Intercept Ask AI requests (e.g., submitting a prompt or selecting a suggested question).Return true to prevent the default modal Ask AI flow. Useful for routing Ask AI into a different UI (e.g., sidepanel) without flicker.

Advanced Options

environment
typeof window
The browser environment object. Useful for testing or SSR scenarios.
portalContainer
DocumentFragment | Element
The container element where the modal should be portaled. Defaults to document.body.
insights
AutocompleteInsights
Insights client integration options to send analytics events.
keyboardShortcuts
DocSearchModalShortcuts
Configuration for keyboard shortcuts. Allows enabling/disabling specific shortcuts.
keyboardShortcuts: {
  'Ctrl/Cmd+K': true,  // Toggle modal
  '/': false           // Disable / shortcut
}
Default: { 'Ctrl/Cmd+K': true, '/': true }

Return Value

DocSearchInstance
object
Returns a DocSearchInstance object with methods and properties for programmatic control.
interface DocSearchInstance {
  readonly isReady: boolean;
  readonly isOpen: boolean;
  open(): void;
  close(): void;
  openAskAi(initialMessage?: InitialAskAiMessage): void;
  destroy(): void;
}

Usage Examples

import docsearch from '@docsearch/js';
import '@docsearch/css';

const search = docsearch({
  container: '#docsearch',
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'YOUR_INDEX_NAME'
});

TypeScript Types

export interface DocSearchProps extends DocSearchCallbacks {
  container: HTMLElement | string;
  appId: string;
  apiKey: string;
  indexName?: string;
  indices?: Array<DocSearchIndex | string>;
  askAi?: DocSearchAskAi | string;
  theme?: DocSearchTheme;
  placeholder?: string;
  searchParameters?: SearchParamsObject;
  maxResultsPerGroup?: number;
  transformItems?: (items: DocSearchHit[]) => DocSearchHit[];
  hitComponent?: (props: HitComponentProps, helpers?: TemplateHelpers) => JSX.Element;
  resultsFooterComponent?: (props: FooterComponentProps, helpers?: TemplateHelpers) => JSX.Element | null;
  transformSearchClient?: (searchClient: DocSearchTransformClient) => DocSearchTransformClient;
  disableUserPersonalization?: boolean;
  initialQuery?: string;
  navigator?: AutocompleteNavigator;
  translations?: DocSearchTranslations;
  getMissingResultsUrl?: ({ query }: { query: string }) => string;
  insights?: AutocompleteInsights;
  portalContainer?: DocumentFragment | Element;
  recentSearchesLimit?: number;
  recentSearchesWithFavoritesLimit?: number;
  keyboardShortcuts?: DocSearchModalShortcuts;
  environment?: typeof window;
  interceptAskAiEvent?: (initialMessage: InitialAskAiMessage) => boolean | void;
}

export interface DocSearchCallbacks {
  onReady?: () => void;
  onOpen?: () => void;
  onClose?: () => void;
}

export interface DocSearchIndex {
  name: string;
  searchParameters?: SearchParamsObject;
}

Build docs developers (and LLMs) love