Techdocs
  • Introduction
  • Implementing Nosto
    • Implement on your website
      • Manual Tagging - Essentials
        • Setting up your account
        • Adding the Nosto Script
        • Adding the Cart Tagging
        • Adding the Customer information
        • Adding the Product Tagging
          • Default Product Tagging
          • Basic Tagging
        • Adding the Category/Brand Tagging
        • Adding the Search Tagging
        • Adding the Order Tagging
        • Defining Nosto placements
        • Tagging your page types
      • Advanced Usage
        • Extending tagging with SKUs
        • Adding support for multi-currency
        • Adding support for customer group pricing
      • FAQ
    • Implement on native mobile
    • Implement on a physical store
    • Implement Search & Categories
      • Using Search Templates
        • Using Search Templates
        • Implementing Search page
        • Implementing Autocomplete
        • Implementing Category pages
        • Testing & deployment
        • FAQ
      • Using the API
        • Use the Search & Categories API
        • Implement Search results page
        • Implement Autocomplete
        • Implement Category pages
        • FAQ
      • Using the JavaScript Library
        • Implement Autocomplete using the Nosto Autocomplete library
          • Installation
          • Initialization
            • Render results
            • Submit search
          • Create Autocomplete template
          • Further reading
    • Check your setup
    • Template customization
      • Starting points
      • Product cards
      • Styling
      • Scripting
  • APIs
    • GraphQL
      • The Playground
      • Using the API
      • Testing and Debugging
      • Using Mutations
        • Updating Products
        • Updating Categories
        • Updating Identities
        • GraphQL: Onsite Sessions
        • Working with Orders
          • GraphQL: Placing Orders
          • GraphQL: Updating Order Statuses
      • Using Queries
        • Querying Products
        • Querying Identities
        • Querying Orders
        • Querying Recommendations
        • Querying Segments
        • Querying Search
        • Querying Category Merchandising Products (CM 1.0)
      • For iOS & Android
      • For Headless
    • REST
      • GDPR
        • Redacting customer data
        • Initiating data takeouts
      • Customers
        • Blacklisting Customers
        • Toggling marketing consent
      • Products
        • Updating Products
        • Discontinuing Products
        • Recrawling Products
      • Other
        • Updating Rates
    • Frontend
      • Session API
        • Terminology
        • Setting up
        • Managing Sessions
        • Handling Placements
        • Tracking Events
        • Leveraging Features
        • Record Attribution
        • Advanced Usage
          • Supporting opt-out and do-not-track
          • Using external session identifiers
          • Adding support for multi-currency
          • Adding support for customer group pricing
        • FAQ
      • JS API
        • Initializing Nosto
        • Recommendations
          • Loading Recommendations
          • Recommendation Callbacks
          • Setting up dynamic filtering
          • Sending Product-View Events
          • Sending Add to Cart-Events
        • Popups
          • Listing Popup Campaigns
          • Opening a Popup
          • Enabling & Disabling Popups
          • Popup Callbacks
        • Advanced Usage
          • Sending email addresses to Nosto
          • Manually segmenting users
          • Dynamically sending the cart content
          • Sending Customer Information
        • Record Attribution
      • Open Source
        • Nosto JS
        • Search JS
        • Nosto React
        • Web Components
          • Loading Web components
  • User Generated Content
    • UGC Techdocs
  • 3rd party data integrations
    • Shopify
    • Magento 2
    • Magento
    • BigCommerce
    • Shopware 6
    • Shopware 5
    • Prestashop
    • Salesforce
    • PHP-SDK
Powered by GitBook
On this page
  • Search
  • Search page
  • Autocomplete
  • Category page
  • Session parameters
  • Analytics
  • Error Handling
  • Search
  • Search form submit
  • Search product click
  • Search add to cart additions
  • Event Tracking Requirements

Was this helpful?

Export as PDF
  1. Implementing Nosto
  2. Implement Search & Categories

Using the JavaScript Library

PreviousFAQNextImplement Autocomplete using the Nosto Autocomplete library

Last updated 2 months ago

Was this helpful?

Search

For client-side/frontend integrations, Nosto's JavaScript library can be used to simplify the integration. It provides a programming interface to access the Search & Categories API.

For the most basic search the fields parameter should be provided to specify what product/keyword fields should be returned. Both products and keywords can be used separately and together, depending on the use case. For all parameters, see the .

nostojs(api => {
    api.search({
        query: 'my search',
        products: { fields: ["name"] },
        keywords: { fields: ["keyword"] }
    }).then(response => {
        console.log(response);
    });
});

The api.search function also accepts the following options:​

Option
Default
Description

redirect

false

Automatically redirect if search returns a redirect

track

null

Track search query by provided type

The function automatically loads session parameters required for personalization & segments in the background.

In order to request custom fields, add the entries "customFields.key" and "customFields.value" to the requested product fields. This changes the example above like this

// ...
        products: { fields: ["name", "customFields.key", "customFields.value"] },
// ...

Search page

For a search page in most cases the facets parameter should be provided.

Also redirect & track should be enabled to automatically track searches to Nosto analytics & redirect if API returns a redirect request.

isKeyword should be set to true if search is submitted by clicking a keyword, suggested in the autocomplete.

nostojs(api => {
    api.search({
        query: 'my search',
        products: {
            facets: ['*'],
            fields: ['name'],
            size: 10
        }
    }, {
        redirect: true,
        track: 'serp',
        isKeyword: true
    }).then(response => {
        console.log(response);
    });
});

Autocomplete

track should be enabled to automatically track searches to Nosto analytics.

nostojs(api => {
    api.search({
        query: 'my search',
        products: {
            fields: ['name'],
            size: 10
        },
        keywords: {
            fields: ['keyword'],
            size: 5
        }
    }, {
        track: 'autocomplete'
    }).then(response => {
        console.log(response);
    });
});

Category page

Furthermore redirect & track should be enabled to automatically track searches to Nosto analytics & redirect if API returns a redirect request.

nostojs(api => {
    api.search({
        products: {
            categoryId: '12345',
            categoryPath: 'Pants',
            fields: ['name'],
            size: 10
        }
    }, {
        track: 'category',
        redirect: true
    }).then(response => {
        console.log(response);
    });
});

Session parameters

For some of the search features to work properly, such as personalised results and segments, the search function needs to be able to access information about the user's session from the front-end.

The search function of the JS API already includes session state automatically.

To get all session data the following snippet can be used:

nostojs(api => {
    api.getSearchSessionParams(options).then(response => {
        console.log(response);
    });
});

The function accepts the following options:

Option
Default
Description

maxWait

2000

Maximum execution time in MS

cacheRefreshInterval

60000

Maximum cache time

Analytics

Tracking search events to analytics can be divided into three parts: search, search submit, search product click. These are user behaviours that should be tracked:

  • search submit (type = serp)

  • faceting, paginating, sorting (type = serp) or (type = category)

  • autocomplete input (type = autocomplete)

  • search results product click (type = serp), (type = autocomplete) or (type = category)

  • autocomplete keyword click (type = autocomplete)

  • category merchandising results (type = category)

JS API library provides tracking helpers for all of these cases.

Error Handling

Search

User actions that lead to search results should be tracked with api.recordSearch() after search request is done:

  • search submit (type = serp) - user submits search query in autocomplete component and is landed to SERP

  • faceting, paginating, sorting (type = serp) or (type = category) - user adjusts current search results by filtering (e.g. brand), selecting search page, sorting results

  • autocomplete input (type = autocomplete) - user sees partial results while typing in search input

  • category merchandising results (type = category) - user sees specific category results when category is selected (category merchandising must be implemented)

You don't need to execute api.recordSearch()if you call api.search(query, { track: 'serp'|'autocomplete'|'category'}) function from JS API, becauseapi.search()already calls api.recordSearch() when track option is provided.

nostojs(async (api) => {

    const searchRequest = {
      query: "shoes",
      products: {
        sort: [{ field: "price", order: "asc" }],
        filter: [{ "field": "brand", "value": "Nike" }]
      }
    }
    const response = await sendGraphQlRequest(searchRequest)
    const searchResult = response.data.search

    api.recordSearch(
        type,
        searchRequest,
        searchResult,
        options
      )
})
Parameter
Description

type

Search type: serp, autocomplete, category

request

result

options (optional)

Record search options. Currently is accepts:

isKeyword: boolean - should be set when keyword in autocomplete is clicked (search is submitted via keyword)

Example:

api.recordSearch(
    "serp",
    {
        query: "shoes",
        products: {
            sort: [{ field: "price", order: "asc" }],
            filter: [{ "field": "brand", "value": "Nike" }]
        }
    },
    {
        products: {
            hits: [{ productId: "123" }, { productId: "124" }],
            fuzzy: true,
            total: 2,
            size: 2,
            from: 0
        }
    },
    {
        isKeyword: false
    }
)

Keyword click tracking

Example:

api.recordSearch(
    'autocomplete', 
    searchRequest,
    searchResult,
    { 
        isKeyword: true
    } 
)

Category results tracking

Example:

api.recordSearch(
    'category',
    {
        products: {
            categoryId: "123456",
            categoryPath: "Pants",
            sort: [{ field: "price", order: "asc" }]
            size: 24,
            from: 0,
        }
    },
    {
        products: {
            categoryId: "123456",
            categoryPath: "Pants",
            hits: [{ productId: "123" }, { productId: "124" }],
            fuzzy: true,
            total: 18,
            size: 24,
            from: 0
        }
    },
    {
        isKeyword: false
    }
)

Search form submit

Search queries are categorised into two groups: organic and non-organic searches. In order to mark a search query as an organic search you need to call api.recordSearchSubmit(query: string). You should call it on search input submit only, before search request is sent.

nostojs(api => {
    const query = 'shoes'
    api.recordSearchSubmit(query)
})

Organic search - is a search query submitted through search input and which lead to SERP (search engine results page). Following faceting, paginating, sorting queries on organic query is also counted as organic.

Search product click

Product clicks should be tracked in autocomplete component, SERP, category page with api.recordSearchClick() by providing component (type), where click occurred, and clicked product data:

nostojs(api => {
    api.recordSearchClick(type, hit)
})
Parameter

type

Search type: serp, autocomplete, category

hit

Object containing productId and url, collected from clicked product

Example:

api.recordSearchClick(
    "autocomplete", 
    { productId: "123", url: "https://myshop.com/product123" }
)

Search add to cart additions

When shopping cart additions happen directly as part of the search or autocomplete results without a navigation to the product page, the api.recordSearchAddToCart() method should be called with the component (type), where addition occurred and the product data:

nostojs(api => {
    api.recordSearchAddToCart(type, hit)
})
Parameter

type

Search type: serp, autocomplete, category

hit

Object containing productId and url, collected from product

Example:

api.recordSearchAddToCart(
    "autocomplete", 
    { productId: "123", url: "https://myshop.com/product123" }
)

When tracking events, adherence to the following criteria is essential for capturing detailed and valid data:

  • query parameter:

    • The query string is an essential component for event tracking.

    • If present, include products.sort to track sorting behavior.

    • If applicable, incorporate products.filter.

  • searchResults parameter:

    • products.hits array containing objects with a productId is mandatory.

    • products.total number to identify if the search has results.

    • For accurate pagination tracking, products.from and product.size must be included.

    • For identifying if the request was autocorrected include products.fuzzy.

    • For category requests, either products.categoryId or products.categoryPathis mandatory.

query {
  search(
    accountId: "YOUR_ACCOUNT_ID"
    query: "green"
    products: { size: 10, from: 10 }
  ) {
    products {
      hits {
        productId
      }
      total
      size
      from
      fuzzy
      categoryId
      categoryPath
    }
  }
}

Bear in mind that search queries are split between organic and non-organic searches. To classify a search as organic, it is crucial to invoke api.recordSearchSubmit() upon the search input submission, before the actual search request is dispatched. This step is pivotal in ensuring the seamless tracking of organic searches through to the SERP.

Tracking product clicks is fundamental for understanding user interaction. Use api.recordSearchClick() to monitor this actions correctly, specifying the type and relevant hit data.

In case of an SPA based integration the api.recordSearchClick calls should be complemented with Session API or api.createRecommendationRequest() usage to couple the search analytics events to generic Nosto events for accurate attribution.


For category pages in most cases the facets parameter should be provided. Additionally (for Shopify) and should be also provided.

The results of this function should be passed to search query parameter. In case search is called from backend, it should pass this data to backend (e.g. using ).

On errors from api.search calls the error object contains a status field that has the HTTP response status which can be used to determine the cause of the error in addition to the error message. The ranges of the status codes used for errors are 400-499 and 500-599. For details on these error codes, go to

The tracking metadata is primarily taken from the third parameter. The and objects must be provided in the api.recordSearch call instead of partials.

Event Tracking Requirements

Tip: In case of API integration, use this example GraphQL partial query to integrate with the API and retrieve the necessary response data for precise event tracking.

Search Form Submit

Accurate Click Tracking

⚠️
⚠️
💡
🚩
🔍
reference
categoryId
categoryPath
sessionParams
form data
HTTP response status codes
full request
full result
Full search API request
Full search API result