Algolia JavaScript Client

repository·main·Indexed 23 days ago

https://github.com/algolia/algoliasearch-client-javascript

A thin, minimal low-level HTTP client for interacting with the Algolia API. Built with TypeScript, it is designed for both browser and Node.js environments and is compatible with UMD and ESM module loaders. The client includes support for A/B testing management, allowing users to create tests, define variants and metrics, analyze time-series data, and evaluate statistical significance via the @algolia/abtesting package.

Tokens
20.3K
Snippets
26
Records
107
Agent score
79%

What's inside algoliasearch-client-javascript

  1. Install the Algolia JavaScript client

    main

    You can install the algoliasearch package using any modern package manager. This client is a thin, minimal low-level HTTP client that works in both browser and Node.js environments and is built with TypeScript.

    yarn add algoliasearch@5.56.0
    # or
    npm install algoliasearch@5.56.0
    # or
    pnpm add algoliasearch@5.56.0
  2. Install the Algolia client via CDN

    main

    If you are not using a package manager, you can include the client directly in your HTML by adding the following script tags to the <head> of your website. You can choose between the full client or the lite client.

    // for the full client
    <script src="https://cdn.jsdelivr.net/npm/algoliasearch@5.56.0/dist/algoliasearch.umd.js"></script>
    
    // for the lite client
    <script src="https://cdn.jsdelivr.net/npm/algoliasearch@5.56.0/dist/lite/builds/browser.umd.js"></script>
  3. Explore the Ingestion model exports

    main

    The packages/ingestion/model package provides the type definitions and data models used for Algolia Ingestion operations. These models cover authentication methods, data sources (such as Shopify, BigQuery, Docker, and CSV), destinations, transformations, tasks, and triggers.

    Key functional areas include:

    • Authentication: Types for various auth methods like authAPIKey, authOAuth, authGoogleServiceAccount, and authBasic.
    • Sources: Definitions for where data originates, including sourceShopify, sourceBigQuery, sourceDocker, sourceCSV, and sourceJSON.
    • Destinations: Definitions for where data is sent.
    • Transformations: Models for data manipulation, including transformationInput, transformationCode, and transformationNoCode.
    • Tasks & Triggers: Management of ingestion workflows via task, trigger, onDemandTrigger, and scheduleTrigger.
    • Runs: Monitoring the execution of ingestion processes through runStatus, runProgress, and runOutcome.

    Note: This file is automatically generated by OpenAPI Generator and should not be edited manually.

  4. Migrate from legacy search and recommendation signatures

    main

    The Algolia JavaScript client has moved away from the v4 signature patterns. In v4, search parameters were often wrapped in a params object. In the current version, the search method accepts flat searchParams at the root of the method call.

    Deprecated Types:

    • LegacyGetRecommendationsParams: An array of RecommendationsRequest. Use GetRecommendationsParams instead for better performance and future-proofing.
    • LegacySearchMethodProps: An array of LegacySearchQuery. Use SearchMethodParams instead for better performance and future-proofing.
    • LegacySearchParams, LegacySearchForFacets, and LegacySearchForHits: These types wrap parameters inside a params key, which is no longer the standard for the search method.
  5. Understand FetchRequester timeout behavior

    main

    The FetchRequester implementation handles two types of timeouts using AbortController:

    1. Connection Timeout (connectTimeout): If the connection is not established within the specified time, the request is aborted and returns a response with status: 0 and content: 'Connection timeout'.
    2. Response Timeout (responseTimeout): If the response body cannot be read within the specified time, the request is aborted and returns a response with status: 0 and content: 'Socket timeout'.

    If a timeout occurs, the returned object will have isTimedOut: true.

  6. Understand search response exhaustivity with the Exhaustive type

    main

    The Exhaustive type is used in search responses to indicate whether certain properties (like hit counts or facet values) are calculated exactly (exhaustive) or via an approximation. When the Algolia engine performs an approximation—often due to complex filters, high query latency, or large result sets—these boolean flags will be false.

    Key properties include:

    • facetsCount: true if the facet count is exact; false if it is approximated.
    • facetValues: false if not all facet values were retrieved.
    • nbHits: true if the total number of hits is exact; false if an approximation was made (common when queries take >50ms or involve complex filters).
    • rulesMatch: false if rules matching could not be fully processed due to a timeout (often caused by too many typo alternatives).
    • typo: true if the typo search was exhaustive; false if an approximation was made (occurs if typo processing exceeds 10% of the query budget, typically 5ms). This field is omitted if typo-tolerance is disabled.
  7. Initialize the Algolia client

    main

    To use the client, import either the full algoliasearch function or the liteClient from the lite subpath. Pass your appId and apiKey to initialize the client instance.

    import { algoliasearch } from 'algoliasearch';
    
    const client = algoliasearch('YOUR_APP_ID', 'YOUR_API_KEY');
    
    // or with the lite client
    import { liteClient } from 'algoliasearch/lite';
    
    const client = liteClient('YOUR_APP_ID', 'YOUR_API_KEY');
  8. Configure attribute retrieval and response fields

    main

    You can optimize API response size by restricting which data is sent back to the client.

    • attributesToRetrieve: An array of strings specifying which attributes to include.
      • Use * to retrieve all attributes (except those in customRanking or unretrievableAttributes).
      • To exclude a specific attribute while retrieving all others, use the syntax: ["*", "-ATTRIBUTE_NAME"].
      • The objectID is always included.
    • responseFields: An array of strings to select specific response properties.
      • Warning: Do not omit the hits field, as your search depends on it.
      • You cannot exclude message, warning, cursor, abTestVariantID, or properties added by getRankingInfo.
  9. Configure createHttpRequester options

    main

    When calling createHttpRequester, you can provide a CreateHttpRequesterOptions object to configure the networking behavior:

    OptionTypeDescription
    agenthttp.Agent | https.AgentA global agent used for both HTTP and HTTPS requests.
    httpAgenthttp.AgentSpecific agent for HTTP requests.
    httpsAgenthttps.AgentSpecific agent for HTTPS requests.
    requesterOptionshttps.RequestOptionsStandard Node.js https.RequestOptions that are merged into every request. This can be used to set default headers, ports, or other low-level socket options.
  10. Configure highlighting and snippets

    main

    Highlighting and snippets help users see why a result matched their query.

    • attributesToHighlight: An array of attributes to highlight. Use * for all or [] to disable. Matches are wrapped in highlightPreTag and highlightPostTag.
    • attributesToSnippet: An array of attributes for which to enable snippets. Snippets include 10 words by default. You can customize the length using the notation ATTRIBUTE:NUMBER (e.g., description:20).
    • highlightPreTag / highlightPostTag: Custom HTML tags to wrap highlighted text.
    • snippetEllipsisText: The string used when a snippet is truncated.
    • restrictHighlightAndSnippetArrays: If true, only items that partially match the query will be highlighted/snippeted.
  11. Configure typo tolerance settings

    main

    Control how strictly Algolia matches words against typos.

    • typoTolerance: Configuration object for typo settings.
    • minWordSizefor1Typo: Minimum characters required for a word to allow one typo.
    • minWordSizefor2Typos: Minimum characters required for a word to allow two typos.
    • allowTyposOnNumericTokens: Whether to allow typos on numbers. Set to false to reduce irrelevant matches in large numeric datasets.
    • disableTypoToleranceOnAttributes: An array of attributes where typo tolerance is turned off (useful for hyphenated attributes or long text blocks like descriptions).