5.2.1 • Published 5 days ago

@klevu/core v5.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 days ago

Klevu

npm.io npm version Bundle size npm total downloads npm weekly downloads github stars github issues npm.io

Come and chat with us: npm.io

@klevu/core

Klevu core is a library that helps developers to interact with Klevu API. It includes a fetching function, easy-to-use functions to perform queries, state management for filters, data transformations and event tracking for easier usage.

The library can run its code in browsers and Node.js.

Api Reference can be found from here

Getting started

> npm install @klevu/core

Initialization

Before making any request it is required to provide the Klevu API key and the search server you are targeting. This should be done in the index of the application or the initialization of your app.

import { KlevuConfig } from "@klevu/core"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
})

If you wish to use Axios to enable SSR or you wish to support old IE browser you can use axios npm package with the library.

First you need to install it into to your project with

> npm install axios

Then import and add it to your configuration.

import { KlevuConfig } from "@klevu/core"
import axios from "axios"

KlevuConfig.init({
  url: "https://<your-server>.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-xxxxxxxxxxxxx",
  axios,
})

Then axios will be used for fetching data.

KlevuFetch

Function queries are inserted into a KlevuFetch() function where functions are processed and sent to the backend.

Here is the most minimal example where we are making a "hoodies" search from the API.

import { KlevuFetch, search } from "@klevu/core"

const result = await KlevuFetch(search("hoodies"))
console.log(result.getQueriesById("search")?.records)

Typical example

The following example finds results based on a term and suggestions what the user could search for next

import { KlevuFetch, search } from "@klevu/core"

// search string coming from a textfield
const term = "hoodies"

const result = await KlevuFetch(
  search(
    // term to search
    term,
    // search parameters
    {},
    // and lastly list of modifiers for the query.
    // In this example we are fetching all filters that are related to the search
    listFilters()
    // More modifiers can be added as parameters to search.
  ),
  // In same fetch we want to fetch all search suggestions also
  suggestion(term)
  // in here we could add more queries to fetch
)

// Prints records that are found from the search
console.log(result.getQueriesById("search")?.records)

Result object

KlevuFetch() result object contains raw API response and handy helpers to get results. Use getSuggestionsById() to fetch suggestions results and getQueriesById() for search results.

getQueriesById() result contains metadata for query, the result records and possible event functions for providing click events to search, category merchandising and recommendations. It also includes next() function. It is a nice helper to fetch the next results set with the same query and modifiers. next() is defined only if there are more results available.

Calling event functions returns a function to use to send events to Klevu. See definition these functions from here

Platform-specific guides

Queries

Queries implement the KlevuFetchFunction interface. Multiple queries can be passed onto KlevuFetch. For example its possible to get suggestions and multiple search results for typed letters in one request.

Detailed information in API reference.

Klevu FunctionDescriptionType
search()Most basic query to find items based on a termSearch
suggestions()Fetches suggestions based on a term.Search
trendingProducts()Find all products that are trending right now in resultsSearch
categoryMerchandising()Products to display on category pageSearch
searchCategory()Search categories based on termSearch
searchCms()Search CMS pages based on termSearch
products()Fetches products by id from KlevuSearch
rawWrite raw request to Klevu api. For expert useSearch
recentlyViewedProducts()List of products user has recently viewedSearch
kmcRecommendation()Fetches predefined recommendation by id from KMC and creates query automaticallyRecommendation
newArrivals()Recommendation list of new arrivals for the current userRecommendation
trendingCategoryProducts()Trending recommendation based for current userRecommendation
similarProducts()Fetch similar products based on given idsRecommendation
alsoViewed()Product recommendations what user should also check outRecommendation
boughtTogether()On checkout page check what products are recommended to current cart productsRecommendation

Modifiers

Some of the functions can be modified with modifier functions. Any number of them can be added to end of query functions

ModifierDescription
listFilters()List all filters that given search result has
applyFilters()Applies selected filters to query
applyFiltersWithManager()Applies filters that's state is managed by FilterManager
fallback()When query returns less results than fallback treshold then additional fallback query is sent
boostWithKeywords()Boost or deboost results with keywords
boostWithRecords()Boost or deboost certain products in the result by id
boostWithFilters()Boost or deboost results based on a filters
boostWithFilterManager()Boost or deboost results based in selection in filter manager
personalisation()Enable personalisation to the query. Automatically applies last visited products
include()Force include given id's in the result
top()Force return given id's as first items on results
sendSearchEvent()When user takes action to search something this should be used
sendMerchandisingViewEvent()Should be used with categoryMerchandising() query to send view event of merchandising
sendRecommendationViewEvent()Should be used with all recommendation queries. Send a analytical data about recommendation to Klevu
debug()Prints query results to console
abTest()Enable A/B testing for the category merchandising
overrideSettings()Allows to override any setting in query. ⚠️ Use with caution!

Filter Manager

Filter Manager is a helper class that takes care of the state of filters. What filters are currently selected and what should be sent. It can be passed to listFilters() and then the result is automatically applied to the state. Modifier applyFiltersWithManager() can base used to apply the current state of filters to query.

Internal DOM events

Core sends a DOM events that any browser library could listen and act on the events. All events are attached to document. KlevuDomEvents enumeration is exposed from the library and it's quite simple to listen. For example:

import { KlevuDomEvents, KlevuListenDomEvent } from "@klevu/core"

// Function to run when filter selection is updated
const handleFilterUpdate = () => {
  console.log("Filter updated")
}

// Attach event listener
const stop = KlevuListenDomEvent(KlevuDomEvents.FilterSelectionUpdate, handleFilterUpdate)

// Don't forget remove event listener in your component destructor
stop()

Or as React example

import React, { useEffect } from "react";
import { KlevuDomEvents, KlevuListenDomEvent } from "@klevu/core";


function MyComponent() {
  const handleFilterUpdate = (event) => {
    console.log(event.detail)
  }

  useEffect(() => {
    const stop = KlevuListenDomEvent(
      KlevuDomEvents.FilterSelectionUpdate,
      handleFilterUpdate
    )

    // cleanup this component
    return () => {
      stop()
    }
  }, [])

  return ...
}

Read more from MDN documentation about Custom Events.

See the list of events from KlevuDomEvents

Events

Klevu requires data for machine learning to work better. KlevuEvents class is low level solution to pass events to Klevu backend.

KlevuEvents.productClick()
MethodDescription
buy()When products are bought
searchProductClick()When product is clicked on search results
search()When search is made. This is automatically sent in the queries
categoryMerchandisingView()When category is displayed. Should be called on paging too
categoryMerchandisingProductClick()When product is clicked in category page
recommendationClick()When product is clicked on list of recommended products
recommendationView()When recommendations are shown

Klevu Merchant Center settings

Users of Klevu can change settings in the Klevu Merchant Center. These settings can be easily fetched with KlevuKMCSettings function.

const result = await KlevuKMCSettings()

Last searches

To get the list of last searches you can use the KlevuLastSearches class.

To get the list of last searches call KlevuLastSearches.get() and if you wish to store a search use KlevuLastSearches.save('user search string')

A/B Testing

Currently A/B testing is supported only in the category merchandising. To enable A/B testing add abTest() modifier to categoryMerchandising() query function.

For A/B testing to work correctly you need to provide correct event data to Klevu. Best way is to use getCategoryMerchandisingClickSendEvent() send event helper from result object .

SSR request packing and hydration

Typically SSR frameworks (Next, Nuxt, Remix, etc) will transfer data from backend to frontend in JSON format. Passing KlevuFetch result object to frontend won't work as it is filled with functions that help the usage of results.

There is an option to just pass raw JSON with result.apiResponse and build your logic on top of that.

If you wish to keep using helper functions provided in results you can use KlevuPackFetchResult() function to pack result like:

const result = await KlevuFetch(search("hello world"))
const dataToTransferFrontend = KlevuPackFetchResult(result)

And then you can hydrate it in frontend with KlevuHydratePackedFetchResult() function.

const resultObject = KlevuHydratePackedFetchResult(dataToTransferFrontend, [search("hello world")])

It's important to note that the second parameter of KlevuHydratePackedFetchResult() has to be the same as in backend call. You can create query functions in a separate file that can be called both in frontend and backend. For example:

// file: myquery.ts
// a bit more compilicated query. Search term can be read in backend
// from request parameters and in frontend it could be in url parameters
const myQuery = (searchTerm: string, manager: FilterManager) => [search(searchTerm, {}, listFilters(), applyFilterwithManager(manager), boostWithKeyword({ keyword: "foobar", weight: 1.2 })), suggestions(searchTerm)]

// file: backend.ts
// in backend manager is not used to set anything so it can be just instanciated as param
const result = await KlevuFetch(myQuery("hello world", new FilterManager()))
const dataToTransferFrontend = KlevuPackFetchResult(result)

// file: frontend.ts
// in frontend we usually want to change and set filters with manager so it's used as separate variable
const manager = new FilterManager()
const resultObject = KlevuHydratePackedFetchResult(dataToTransferFrontend, myQuery("hello world", manager))
console.log(manager.options)

Data Protection

For customers who need to comply with data protection rules, you can enable data protection in the SDK by setting the useConsent to true and then setting the consentGiven value to true when you receive the consent from the user. By default, the data protection is turned off. You can use the following code snippet as an example to set it up

KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  useConsent: true, //Either set it to true during initialization
  consentGiven: true, //Either set it to true during initialization
})
// or
KlevuConfig.getDefault().setUseConsent(true)
KlevuConfig.getDefault().setConsentGiven(true) // When you receive the user consent

If useConsent is enabled, then no user data will be used by Klevu till the consentGiven is enabled.

Using Klaviyo for segmentation

To enable Klaviyo integration for segemntation in Recommendations, set enableKlaviyoConnector to true.

KlevuConfig.init({
  url: "https://eucs23v2.ksearchnet.com/cs/v2/search",
  apiKey: "klevu-160320037354512854",
  enableKlaviyoConnector: true, //To enable Klaviyo integration for segmentation in Recommendations
})

Setitng enableKlaviyoConnector to true will make all the necessary internal configuration changes for Klevu Recommendations to work with Klaviyo segments.

You should consider using this feature with Data protection settings if there is a need to meet any legal requirements. If Data Protection is enabled, then no user data will be stored unless the consent is given.

Check above for more information.

5.2.1

5 days ago

5.2.0

20 days ago

5.1.0

2 months ago

5.0.0

4 months ago

3.4.0

8 months ago

3.0.4

10 months ago

3.0.3

10 months ago

3.2.0

9 months ago

3.0.2

10 months ago

3.0.1

10 months ago

3.6.0

8 months ago

3.0.0

10 months ago

4.0.1

6 months ago

4.0.0

6 months ago

4.0.2

6 months ago

2.0.13

10 months ago

2.0.11

11 months ago

2.0.12

10 months ago

3.3.0

8 months ago

3.1.0

9 months ago

3.5.0

8 months ago

2.0.3

12 months ago

2.0.2

12 months ago

2.0.5

12 months ago

2.0.4

12 months ago

2.0.7

11 months ago

2.0.6

12 months ago

2.0.9

11 months ago

2.0.8

11 months ago

2.0.1

1 year ago

2.0.0

1 year ago

2.0.10

11 months ago

1.10.2

1 year ago

1.10.1

1 year ago

1.10.0

1 year ago

1.9.0

1 year ago

1.8.0

1 year ago

1.7.0

1 year ago

1.6.1

2 years ago

1.6.0

2 years ago

1.5.0

2 years ago

1.4.0

2 years ago

1.2.0

2 years ago

1.1.6

2 years ago

1.3.0

2 years ago

1.2.1

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago

0.0.25

2 years ago

1.1.2

2 years ago

0.0.26

2 years ago

0.0.20

2 years ago

0.0.21

2 years ago

0.0.22

2 years ago

0.0.23

2 years ago

0.0.24

2 years ago

0.0.15

2 years ago

0.0.16

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.19

2 years ago

0.0.11

2 years ago

0.0.12

2 years ago

0.0.13

2 years ago

0.0.14

2 years ago

0.0.3

2 years ago

0.0.10

2 years ago

0.0.2

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.1

2 years ago