# Introduction
> Source: https://docs.recombee.com
> For the complete documentation index, see [llms.txt](/llms.txt).
# Introduction
Recombee is a Recommender as a Service with easy integration and powerful Admin UI.
The Recombee recommendation engine can be applied to any domain that has a catalog of items and is interacted by a large number of users. Applicable to web and mobile apps, Recombee improves user experience by showing the most relevant content for individual users.
## How It Works

[**Item properties**](/getting_started#defining-item-properties) describe the products or content that you want to recommend to the users. You can define various types of properties that are analyzed by the content-based recommendation models. In addition to that, you can also use the data in your [Filter or Booster rules](/reql). Data can be delivered using a [Catalog Feed](/catalog_feeds) or the [Recombee API](/api).
**User properties** (optional) contain data about your users. Data can be delivered using the [Recombee API](/api/users).
**Interactions** between Users and Items are the most important data for the recommender system, as the collaborative filtering models learn various relations from them. You can send them using the [No-Code Widget](/no-code-widgets), [Client-Side API](/api_clients), [Server-Side API](/api_clients), or [Segment Integration](/segment).
**Scenarios** define a particular application of a recommendation at your website, mobile app, or email. They may be _homepage-featured_, _watch-next_, _read-next_, _similar-products_, _emailing-after-purchase_, or others. Each Scenario is of a particular **recommendation type**. The type can be for example: a recommendation for a particular user, recommendation of related items, or a personalized full-text search. You can also apply various settings to each Scenario.
[**Recommendation Logic**](/logics) specifies the desired behavior of the recommendation model. We have prepared different [Logics for various use-cases](/logics) that you can choose from.
[**Business Rules**](/reql#business-rules) are used to filter or boost items based on their properties. We provide a library with frequently used Rules that you can apply out-of-the-box - and start using immediately. You can also specify your own Rules using our intuitive [Recombee Query Language (ReQL)](/reql).
[**Constraints**](/scenarios/settings-in-admin-ui#constraints) allow you to configure how items with shared conditions may repeat within the recommendation results.
You can integrate recommendations using our [No-Code widget](/no-code-widgets), our [Widget SDKs](/widget-sdks), or [API SDKs](/api_clients) in the programming language of your choice.
## Where to Use
Recombee can be **utilized in various domains:**
* Video
* Articles, News, Media
* E-commerce
* Music, Podcasts
* Marketplaces
* Real estate
* Job boards, HR, Networking
* Travel, Trips
* and many more
Thanks to our simple integration process, you will be able to provide **content, product, or specialized personalization** on your **website, web app, mobile app, or emailing** in a short time.
**Personalized Search, Homepage, Product/Content detail page, Push notifications,** recommended content in **Read next or Watch next** \- those are only a few examples of how you can apply Recombee personalization to improve UX and loyalty of your users.
* Personalized search
* Featured on homepage
* Newsletter
* Read next
* Watch next
* Similar products
* Similar content
* Other also bought
* Push notifications
* etc.
## Let’s Start with Integration
[Getting Started Guide: Step-by-step integration](/getting_started)[HTML Integration: Using our No-Code widget](/no-code-widgets)[Integration Tips: Achieve better performance](/integration_tips)
---
# Getting Started
> Source: https://docs.recombee.com/getting_started
> For the complete documentation index, see [llms.txt](/llms.txt).
# Getting Started
The first thing you need is to set up a database at Recombee. Sign up for a free instant account at [recombee.com](https://www.recombee.com) if you haven't already.
We provide [client libraries (SDKs)](/api_clients) for languages such as JavaScript, Java, Ruby, Python, .NET, PHP and more, which makes the integration very easy.
If you don't use any of the supported languages, you also have the ability to use the REST API directly. See the [authentication page](/authentication) for more details.
## How to Integrate
Integration consists of four main parts:
[Sending Interactions](#getting-started-interactions)[Synchronizing the Item Catalog](#getting-started-catalog)[Showing Recommendations](#getting-started-recomms)[Personalized Search](#getting-started-search)
Each of these parts can be achieved in multiple ways.
The recommendations are usually shown to a user on a website, in a mobile app or within an email campaign.
If you're using an **AI agent or assistant** to integrate Recombee into your application, the documentation includes [an integration guide](/ai_assistant_guide) written specifically for AI assistants. You can use the prompt below as a starting point:
Initial Prompt
Use this prompt with AI agents to integrate Recombee into your application.
```
Integrate Recombee (a recommendation engine) into my application.
Before writing any code, fetch and read the integration guide at https://docs.recombee.com/ai_assistant_guide.md.
It's written specifically for AI assistants and covers authentication, catalog sync, interactions, recommendations, and common pitfalls.
Use it as your primary reference.
First, explore the codebase to understand the stack, data models, and integration points.
Then propose a plan before implementing anything.
Do not decide on your own where recommendations should appear.
Ask me which use cases to implement — homepage recommendations, related items on a product page, personalized search, email suggestions, and so on.
The right surfaces depend on my product and priorities, so treat that as a shared decision even when you're otherwise working autonomously.
After we agree on the use cases, implement them end to end, and flag any assumptions you have to make along the way.
```
## Sending Interactions
Interactions are the most valuable information for the algorithms in the recommender engine.
The interactions that you send are used by the recommender engine in finding out which items are popular, as well as which recommendations perform the best. There are [multiple kinds](/api/interactions) of interactions that are supported.
For example, a [Detail View](/api/interactions#add-detail-view) is sent every time a user views the detail of an item, while a [Purchase](/api/interactions#add-purchase) is sent every time a user completes the main desired goal (a conversion). In most cases, you will want to send multiple kinds of interactions as part of your integration.
Keep in mind that the names of interaction types may not have the same meaning in your business compared to how they are used in Recombee. For example, an event that is called a [Purchase](/api/interactions#add-purchase) in Recombee may not necessarily mean that the user has bought something, but could also mean that the user replied to an advertisement or watched a video until the end.
You can send interactions using one of the following methods:
[API Integration: Call the API and use your own code to send the interactions.](#getting-started-interactions-sdk)[Segment Integration: Use the Recombee Destination within the Segment CDP to send interactions in a unified way.](/segment)
### Using the API SDK
Sending interactions using the API SDK is very easy. Let's say we want to send a [Detail View](/api/interactions#add-detail-view) interaction for item `xyz` by user `2c169e`:
```js
// Import the library using npm or using the script tag:
//
const client = new recombee.ApiClient('myDb', publicToken, {region: 'us-west'});
await client.send(new recombee.AddDetailView('2c169e', 'xyz'));
```
There are a few important parameters in the above code:
* `myDb` is the name of the database you are sending data to **(required)**,
* `publicToken` or `privateToken` is the [access token](https://admin.recombee.com/go-to-database/settings) for the given database **(required)**,
* `region` is the [region](/regions) where your DB is located _(recommended)_,
* `itemId` is a unique identifier of the item **(required)**,
* `userId` is a unique identifier of the user **(required)**. For anonymous users, you can use a session ID.
**Optional parameters:**
* `timestamp` is a UNIX timestamp or ISO 8601 date-time of the view. If not specified, the current time is used.
* `cascadeCreate` tells the system that it should create the item or the user if it doesn't exist yet.
If not specified, it is set to `true` in client-side SDKs and `false` in server-side SDKs.
We recommend that you use this parameter to prevent errors in case the item or user doesn't exist yet.
Interactions also have optional parameters unique to each type, such as `duration` for [Detail View](/api/interactions#add-detail-view) or `profit` for [Purchase](/api/interactions#add-purchase). You can find the full list of parameters in the [API documentation](/api/interactions).
### Handling Anonymous Users
You may encounter a situation where a user comes to the site as an anonymous user and logs into a regular account later. This is especially the case in e-commerce.
However, ideally, you want to track the interactions of the anonymous user before they log in and then use that data to provide better recommendations after they log in.
To handle this situation, you can use the following approach:
* For anonymous users, use a session ID or another unique identifier (e.g. a randomly generated ID consistent across the session) as the `userId` parameter when sending interactions.
* For logged-in users, use their user ID as the `userId` parameter.
* When a user logs in, send a [Merge Users request](/api/users#request-merge-users) to merge the anonymous user with the regular account. This way, all interactions of the anonymous user will be transferred to their account and the anonymous user ID will be deleted.
### Reporting Successful Recommendations
Once you have integrated recommendations into your site or application, it is **very important** to report the success of these recommendations, as without it, the system will not be able to get precise feedback and improve the quality of future recommendations.
You should report a successful recommendation by adding a parameter called `recommId` to all interactions which are based on that recommendation. For example, if a user views an item that was recommended to them, you should send the `recommId` of that recommendation with the [Detail View](/api/interactions#add-detail-view). If they then purchase the item, you should also send the `recommId` with the [Purchase](/api/interactions#add-purchase).
You can find the `recommId` in the Recommendation object that you receive from the API:
```
{
"recommId": "968d7864-1d52-4525-a37f-d5b7dd86fe13",
"recomms": [
{
"id": "item-146"
},
{
"id": "item-462"
}
],
"numberNextRecommsCalls": 0
}
```
You can then use this value in an optional parameter in all interaction requests in all Recombee API SDKs, as well as in the Segment integration. For the API SDK, you can find a code example in the [API Reference](/api/interactions#add-detail-view).
As a result of sending the `recommId` with your interactions, the models will be able to return better recommendations and you will also get [precise success metrics in the Admin UI](/admin_ui#reported-metrics).
There need to be enough interactions in the system for it to produce quality recommendations, so it may take some time before the best recommendations are produced.
If you're looking to improve the performance of the models beforehand, we recommend that you submit a historical log of past interactions. To achieve this, you can use the [Batch API endpoint](/api/miscellaneous#batch) to send multiple interactions in a single request.
## Updating the Item Catalog
The second most important kind of data for the recommender system is information about the items (e.g, names, descriptions, categories).
The data that you send about the items is used in multiple ways:
* It can be used for filtering and boosting recommendation results with [ReQL](/reql), allowing you to influence the recommender engine.
* It can be returned when getting recommendations to show to the users, so that you don't have to make additional requests to your database to get the item details.
* It is also used to compute the recommendations, especially when the items have very few interactions (e.g., newly added items).
There are two possible methods of updating the item catalog:
[API Integration: Call the API and use your own code to send the item catalog.](#getting-started-catalog-sdk)[Catalog Feed: Set up a feed that will automatically synchronize your item catalog with Recombee.](/catalog_feeds)
### Using the API SDK
For security reasons, it is possible to change the item catalog only from **server-side SDKs** or using the API with a private token.
#### Defining Item Properties
Before sending the data, you first have to define the properties of the items that you want to submit to the system.
Creating an Item Property is in a way similar to adding a column to the table of items, while submitting an item is like adding a row to the table.
**The following Item Property types are available:**
* **String**
* **Integer** \- integer number
* **Double** \- floating point number
* **Boolean** \- true / false
* **Timestamp** \- UTC timestamp
* **Set** \- a set of strings
* **Image** \- URL of an image
* **Image List** \- array of image URLs
The default value for all created properties is `null`.
To create or remove Item Properties, you can use the [appropriate API calls](/api/item-properties), or do it manually in the [Admin UI](/admin_ui).
For examples of properties that can be useful for the recommender engine, see [Integration Tips](/integration_tips). You can also assign semantic roles and metadata to your properties - see [Property Roles & Metadata](/api/property_roles_metadata) for the full reference.
[](/img/gui/add_property.png)
#### Sending Item Values
Let's say we've added some item properties to our database, and now want to set their values for a particular item `xyz`.
This can be done by using the [Set Item Values](/api/item-properties#set-item-values) request:
```python
client.send(SetItemValues('xyz',
{
"title": "Television TV2305",
"description": "HD resolution LED TV",
"price": 200,
"categories": ["Electronics", "Televisions"],
"image": "http://examplesite.com/products/xyz.jpg",
"deleted": False
},
cascade_create=True
))
```
The `cascadeCreate` parameter indicates that the item of the given `itemId` should be created if it does not exist in the database.
After sending the above request, you can check that the values have been successfully set in the Admin UI.
If you wish to send an entire catalog, sending a request for each item separately may be quite slow. To speed up the process, we recommend using [Batch requests](/api/miscellaneous#request-batch).
In addition to Item Properties, the system also supports [User Properties](/api/user-properties#subsection-values-of-user-properties). These work in a similar way, but are used to describe the users instead of the items. Learn more in the [User Properties API section](/api/user-properties).
Tip
Still not sure on how to implement sending of the Item Catalog? See the[Tutorial](/tutorial#tutorial-catalog) for more details.
## Getting Recommendations
Now it's time to get some recommendations!
There are three possible ways to get recommendations onto your site:
[API Integration: Call the API and use your own code to show the resulting recommendations to your users.](#getting-started-recomms-sdk)[No-Code Widget: Use the visual editor in the Admin UI and paste the provided embed code into your site.](/no-code-widgets)[Widget SDKs: Use a suite of customizable components to quickly embed recommendations into your site.](/widget-sdks)
### Using the API SDK
We will use two endpoints:
* [Recommend Items to User](/api/recommendations#request-recommend-items-to-user) \- The system recommends items to a given user depending on the user's personal taste. This case can be used for example on your homepage.
* [Recommend Items to Item](/api/recommendations#request-recommend-items-to-item) \- The system recommends items that are related to a given item. The system can also take into account the target user, which can be useful on the page of a product or article, since the endpoint will give the user a list of related items that they might also be interested in.
#### Recommend Items to User
Getting 5 recommendations for user `2c169e` is very easy:
```js
const recommended = await client.send(new recombee.RecommendItemsToUser('2c169e', 5));
```
An object with recommended items in the `recomms` field is returned. It can look like this:
JSON
```
{
"recommId": "968d7864-1d52-4525-a37f-d5b7dd86fe13",
"recomms": [
{
"id": "item-146"
},
{
"id": "item-462"
},
{
"id": "item-463"
},
{
"id": "item-1555"
},
{
"id": "item-683"
}
]
}
```
Besides the IDs of the recommended items, a unique `recommId` is returned. It can be used for several purposes:
* It allows you to [report the success of recommendations](#reporting-successful-recommendations), which gives you metrics in the Admin UI, while also allowing the recommender engine to improve its quality.
* It enables you to fetch another set of recommendations for the same user without repeating the ones you have already displayed, which is useful for implementing [Infinite Scroll & Pagination](#infinite-scroll-pagination).
#### Recommend Items to Item
Getting recommendations based on item `xyz` which is viewed by user `2c169e` is also easy:
```js
const recommended = await client.send(
new recombee.RecommendItemsToItem(
'xyz', '2c169e', 10,
{
'scenario': 'product_detail',
'returnProperties': true,
'cascadeCreate': true
}
)
);
```
In this case, three optional parameters were also set: `scenario`, `returnProperties`, and `cascadeCreate`.
A [Scenario](/scenarios) defines a particular application of recommendations on your website, your mobile app or emailing campaign. Some examples can be _homepage_, _watch-next_, _product-detail_, _cart_, or _emailing-after-purchase_.
For each of the [Scenarios](/scenarios), various parameters can be set in the [Recombee Admin UI](https://admin.recombee.com/go-to-database/scenarios):
* **[Logic](/logics)**, which specifies the desired behavior of the recommendation model.
* **[Filters](/scenarios/settings-in-admin-ui#filters) & [Boosters](/scenarios/settings-in-admin-ui#boosters)**, by which you specify your [business rules](/reql#business-rules) (which items can be recommended and which items should be preferred).
* **[Constraints](/scenarios/settings-in-admin-ui#constraints)**, by which you can specify the number of allowed items in the recommendation response per category, brand, or other criteria.
See [Integration Tips](/integration_tips) for examples of typical scenarios in a particular domain (media, e-commerce, real estate, etc.) and their suggested settings.
You can also customize the above parameters via the API. For more details see the [Recommendations API section](/api/recommendations).
[](/img/gui/setting_scenario.webp)
Setting Logic & Filter in the Admin UI
#### Recommend Item Segments
Recombee can also recommend Item Segments such as categories, genres, or brands. See [Segmentations](/segmentations) for more information, including how to set them up and use them for recommendations.
#### Tips and Tricks
The API can also return the properties of the recommended items, which you can then use to display these items to your users.
To enable this, set `returnProperties = true` when requesting recommendations.
We also recommend that you use the `includedProperties` parameter to specify which properties you want to receive in the response.
[Learn more](/api/recommendations#recommend-items-to-user-param-returnProperties)
If the given user or item does not exist in the system yet (for example because the item catalog is updated periodically only once a day) the default behavior is to return an error (HTTP 404).
Setting `cascadeCreate = true` tells the recommender to rather create the missing item/user instead.
Some bestsellers/trending content will be recommended to these completely new (cold start) items/users without interactions and properties. `cascadeCreate` is set to `true` by default in client-side SDKs.
[Learn more](/api/recommendations#recommend-items-to-user-param-cascadeCreate)
If you are implementing features like infinite scroll or pagination, you can use the [Recommend Next Items](/api/recommendations#recommend-next-items) endpoint to load recommendations based on the previous pages.
This means you can fetch the next set of recommended items without repeating the ones you have already displayed.
To use this functionality, you must provide the `recommId` from the initial recommendation request.
[Learn more](/api/recommendations#recommend-next-items)
Recombee can also recommend Users instead of Items.
For this purpose, we provide [Recommend Users to Item](/api/recommendations#recommend-users-to-item) and [Recommend Users to User](/api/recommendations#recommend-users-to-user) endpoints.
[Learn more](/api/recommendations#recommending-users)
Tip
Still not sure on how to implement sending interactions & getting recommendations? See the[Tutorial](/tutorial#tutorial-interactions-recommendations) for more details.
## Personalized Search
Our personalized full-text search enhances the search experience on your site.
Besides recommendations, Recombee can also provide personalized search results. This means that the search results take into account the user's preferences and behavior, not just the search query.
There are three possible ways to implement search on your site:
[API Integration: Call the search API and use your own code to show the returned items to your users.](#getting-started-search-sdk)[No-Code Widget: Use the visual editor in the Admin UI and paste the produced embed code into your site.](/no-code-widgets#html-widget-full-text-search)[Widget SDKs: Use a suite of customizable components to quickly embed search into your site.](/widget-sdks#quick-search)
### Using the API SDK
Search can be implemented using the [Search Items](/api/search#search-items) and [Search Item Segments](/api/search#search-item-segments) API endpoints.
```js
const matches = await client.send(
new recombee.SearchItems(
'user-13434', 'search query', 5,
{
'scenario': 'search_top',
'returnProperties': true,
'cascadeCreate': true
}
)
);
```
---
# Concepts & Glossary
> Source: https://docs.recombee.com/concepts-and-glossary
> For the complete documentation index, see [llms.txt](/llms.txt).
# Concepts & Glossary
This page describes the basic terminology that is used across this documentation.
[Catalog: A list of entities (Users or Items) along with their properties.](/getting_started#getting-started-catalog)
[Items: The content, products, or other entities that Recombee recommends or returns in search results.](/getting_started#getting-started-catalog)
[Item Properties: Attributes that describe Items, such as title, category, price, availability, or publication date.](/getting_started#defining-item-properties)
[Users: Users who interact with Items and get recommendations.](/api/users)
[User Properties: Optional attributes that describe Users, such as language, country, or subscription type.](/api/user-properties#subsection-values-of-user-properties)
[Series: Ordered collections of Items, used mainly in the video domain to represent shows, seasons, and episodes.](/integration_tips#modeling-series)
[Interactions: Events that record how Users engage with Items, such as views, purchases, ratings, or bookmarks.](/getting_started#getting-started-interactions)
[recommId: A unique identifier of a recommendation request, used to attribute subsequent Interactions to the recommendation that caused them.](/getting_started#reporting-successful-recommendations)
[Scenario: A specific place on a website, in an application, or in an email where recommendations or search results are presented. Each Scenario can be configured to match the intended behavior for the use case.](/scenarios)
[Logic: The recommendation model ensemble used to compute recommendations or search results in a Scenario.](/logics)
[Business Rules: Rules that adapt recommendation results to business requirements.](/reql#business-rules)
[Filters: Rules that determine which Items can appear in the results.](/scenarios/settings-in-admin-ui#filters)
[Boosters: Rules that make the recommender prefer some Items over others.](/scenarios/settings-in-admin-ui#boosters)
[Constraint: A rule that controls how frequently Items sharing a condition can appear in recommendation results.](/scenarios/settings-in-admin-ui#constraints)
[ReQL: Recombee Query Language, used to create custom Filters, Boosters, and advanced Item Segmentations.](/reql)
[Item Segmentation: A way to group Items into Segments based on their properties. The Segments can then be used to recommend the top categories, genres, artists, or a personalized ordering of homepage sections to users and can also be used in analytics.](/segmentations)
[Insights: Analytics in the Recombee Admin UI for exploring recommendation and Interaction data.](/insights)
[SDKs: Lightweight client libraries for integrating the Recombee API in various server-side and client-side programming languages.](/api_clients)
[Widget SDKs: Customizable components for adding Recombee recommendations and search to JavaScript or React applications.](/widget-sdks)
[No-Code Widgets: Recommendation and search components created in a visual editor in the Recombee Admin UI and added to a website using an embed code.](/no-code-widgets)
---
# API Clients (SDKs)
> Source: https://docs.recombee.com/api_clients
> For the complete documentation index, see [llms.txt](/llms.txt).
# API Clients (SDKs)
We provide clients for multiple programming languages. These helper libraries make the integration of our service into your web or application faster and easier.
We offer both _client-side_ and _server-side_ SDKs. The differences are summarized in the table below:
| Client-side SDK | Server-side SDK | |
| ------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------- |
| Running in | Browser or mobile apps | Server-side scripts |
| Supported endpoints | [Interactions](/api/interactions), [Recommendations](/api/recommendations) & [Search](/api/search) | Everything from [API Reference](/api) |
| Type of token used | Public token (for security reasons) | Private token |
The following languages are supported via client-side SDKs:
[JavaScript](/js_client)[Kotlin (Android)](/kotlin_client)[Swift (iOS)](/swift_client)
The following languages are supported via server-side SDKs:
[Java](https://github.com/recombee/java-api-client)[Ruby](https://github.com/recombee/ruby-api-client)[Node.js](https://github.com/recombee/node-api-client)[PHP](https://github.com/recombee/php-api-client)[Python](https://github.com/recombee/python-api-client)[.NET](https://github.com/recombee/net-api-client)[Go](https://github.com/recombee/go-api-client)
You can combine multiple SDKs - for example you can use [JavaScript](/js_client) for sending [interactions](/getting_started#getting-started-interactions) and getting recommendations, but [synchronize the Catalog](/getting_started#getting-started-catalog) using a server-side SDK (e.g. [Python](/python_client)).
For more information on the available API endpoints, including examples for all supported languages, see the [API Reference](/api).
---
# JavaScript API Client
> Source: https://docs.recombee.com/js_client
> For the complete documentation index, see [llms.txt](/llms.txt).
# JavaScript API Client
This library allows you to request recommendations and send interactions between users and items (such as views, bookmarks, or purchases) to Recombee. It is a thin wrapper around the [Recombee API](/api) and provides a simple way to interact with it.
Client-side SDK
This SDK is designed for use in browser-based or other client-side applications, including frameworks like React Native and NativeScript.
For server-side integration with the Recombee API, use our dedicated [Node.js library](https://github.com/recombee/node-api-client)or other available [server-side SDKs](/api_clients#server-side).
To use this client-side SDK in a full-stack framework (e.g., Nuxt or Next.js), additional configuration is required.
For security reasons, it is not possible to change the item catalog, such as the properties of items, using this SDK. To send your Catalog to Recombee, use one of the following methods:
* Use one of our server-side SDKs, for example using a script which runs periodically (see [Managing Item Catalog](/getting_started#getting-started-catalog) for more details),
* Or set up a [Catalog Feed](/catalog_feeds) in the [Admin UI](https://admin.recombee.com/).
[GitHub: See the implementation, contribute, or report issues](https://github.com/Recombee/js-api-client)[API Reference: List of all available endpoints with examples](/api)
## Install
There are two ways to include the library in your project:
**1\.
```
If you require, you can download [recombee-api-client.min.js](https://github.com/recombee/js-api-client/blob/master/dist/recombee-api-client.min.js) and host it on your site or CDN.
```
```
After this script is included, you can access the API Client using the global `recombee` object.
Alternatively, if you want to use the library in ESM code, you can import `recombee-api-client.min.mjs` as follows:
```
```
**2\. Package managers:**
Alternatively, you can install the SDK via a package manager:
```npm
npm install recombee-js-api-client
```
Afterwards, you can import the `recombee` object as follows:
```
import recombee from 'recombee-js-api-client'
// or
const recombee = require('recombee-js-api-client');
```
The library ships with types, so you should get autocompletion in your IDE out of the box. If you're using TypeScript, it should recognize these correctly and warn you about any type errors.
## Configure
In order to use the API, you will need to create an instance of the `ApiClient` class. You will need:
* the **ID of your database**,
* the **public token**.
You can find these in the Admin UI, in [your Database's Settings page](https://admin.recombee.com/go-to-database/settings), under **API ID & Tokens**. Along with this information, you can also find the full code snippet for initializing the client, including the above-mentioned parameters.
Ideally, you should only have one instance of the `ApiClient` in your application, as it is a lightweight object and can be reused for multiple requests. Feel free to export it from a module and import it wherever you need it.
```
// Initialize the API client with the ID of your database and the associated PUBLIC token
export const client = new recombee.ApiClient('database-id', '...db-public-token...', {
region: 'us-west', // the region of your database (default: 'eu-west')
});
```
You can also set several optional parameters when initializing the client:
```
const client = new recombee.ApiClient('database-id', '...db-public-token...',
{
// Use this if you were assigned a custom URI by the Recombee Support team (default: none)
baseUri: 'custom-uri.recombee.com',
// Whether to use HTTPS - can be used for debugging (default: true)
useHttps: true,
}
);
```
## Send Interactions
After you have initialized the client, you can send interactions between users and items.
The individual interactions are classes within the `recombee` object (e.g. `recombee.AddBookmark`, `recombee.AddPurchase`, etc.). After you create an instance of the interaction, you can send it using the `send` method of the client.
Each interaction has both mandatory and optional parameters.
The most important optional parameter is `recommId` \- the ID of the recommendation to which the interaction belongs. Providing this ID allows you to track successful recommendations. For more information, read about [Reported Metrics](/admin_ui#reported-metrics).
For a full list of interactions, along with their parameters, refer either to the types in the library or the [API Reference](/api).
```
// Either create the interaction first and then send it
const bookmark = new recombee.AddBookmark('user-13434', 'item-256');
await client.send(bookmark);
// Or send it directly
await client.send(new recombee.AddCartAddition('user-4395', 'item-129', {
recommId: '23eaa09b-0e24-4487-ba9c-8e255feb01bb',
}));
await client.send(new recombee.AddDetailView('user-9318', 'item-108'));
await client.send(new recombee.AddPurchase('user-7499', 'item-750'));
await client.send(new recombee.AddRating('user-3967', 'item-365', 0.5));
await client.send(new recombee.SetViewPortion('user-4289', 'item-487', 0.3));
```
If you want to send multiple interactions at once, you can use the `Batch` request:
```
const batch = new recombee.Batch([
new recombee.AddBookmark('user-13434', 'item-256'),
new recombee.AddCartAddition('user-4395', 'item-129', { cascadeCreate: true }),
new recombee.AddDetailView('user-9318', 'item-108'),
]);
await client.send(batch);
```
You can then use `try/catch` to handle any errors that may occur.
```
try {
await client.send(
new recombee.AddPurchase('user-14125', 'item-137', { cascadeCreate: true })
);
console.log('Purchase sent');
} catch (err) {
console.error('Error sending purchase:', err);
}
// Console: Purchase sent
```
## Get Recommendations
With an initialized client, you can also request recommendations.
There are multiple types of recommendations, such as:
* [Recommend Items to User](/api/recommendations#recommend-items-to-user),
* [Recommend Items to Item](/api/recommendations#recommend-items-to-item),
* [Recommend Item Segments to User](/api/recommendations#recommend-item-segments-to-user) (these can be categories, genres, artists, etc.),
* or [others](/api/recommendations).
Each recommendation request is a class within the `recombee` object (e.g. `recombee.RecommendItemsToUser`, `recombee.RecommendItemsToItem`, etc.).
After you create an instance of the recommendation request, you can send it using the `send` method of the client.
| Promise | |
| ---------- | --------------------------------- |
| On success | Return value is a Response object |
| On error | Throws an Error |
```
// Get 5 recommendations related to 'item-356' for 'user-13434'
const response = await client.send(
new recombee.RecommendItemsToItem("item-356", "user-13434", 5)
);
console.log(response);
// {
// recommId: 'f080784b-1e8b-4328-8d59-28d962301007',
// recomms: [
// {
// id: 'item-123',
// values: { title: 'Product 123', img_url: 'https://example.com/img123.jpg' }
// },
// {
// id: 'item-456',
// values: { title: 'Product 456', img_url: 'https://example.com/img456.jpg' }
// },
// ...
// ]
// }
```
For a full list of request parameters and possible responses, visit the [API Reference](/api/recommendations).
### Personalized Search
[Personalized full-text search](/api/search#search-items) is requested in the same way as recommendations:
```
const searchQuery = " ... search query from search field ....";
const response = await client.send(
new recombee.SearchItems("user-13434", searchQuery, 5)
);
console.log(response);
// {
// recommId: 'f080784b-1e8b-4328-8d59-28d962301007',
// recomms: [
// {
// id: 'item-123',
// values: { title: 'Product 123', img_url: 'https://example.com/img123.jpg' }
// },
// {
// id: 'item-456',
// values: { title: 'Product 456', img_url: 'https://example.com/img456.jpg' }
// },
// ...
// ]
// }
```
### Recommend Next Items
If you are implementing features like infinite scroll or pagination, you can use the `RecommendNextItems` request to load recommendations progressively.
This means you can fetch the next set of recommended items without repeating the ones you have already displayed.
To use this functionality, you must provide the `recommId` from the initial recommendation request.
For more details, see the [Recommend Next Items](/api/recommendations#recommend-next-items) documentation.
```
// Fetch the initial set of 5 recommendations for user-13434
const initialRecomms = await client.send(
new recombee.RecommendItemsToUser("user-13434", 5)
);
// Get the next 3 recommendations as user-13434 scrolls down
const nextRecomms = await client.send(
new recombee.RecommendNextItems(initialRecomms.recommId, 3)
// Use the recommId from the previous request ^
);
```
### Batch Requests
You may encounter a situation where you display recommendations in multiple places on your website.
In such cases, you can use the `Batch` request to send multiple recommendation requests at once. This can help reduce the number of HTTP requests and improve performance.
For example, you can request the most popular items, as well as items related to a specific user or item, in a single Batch:
```
const batch = new recombee.Batch(
[
new recombee.RecommendItemsToItem("item-356", "user-13434", 5, { scenario: "because-you-watched" }),
new recombee.RecommendItemsToUser("user-13434", 5, { scenario: "new-releases" }),
new recombee.RecommendItemsToUser("user-13434", 5, { scenario: "popular" }),
],
{
distinctRecomms: true,
}
);
const responses = await client.send(batch);
for (const response of responses) {
console.log("Because You Watched:", response[0]);
// Because You Watched: { recommId: '...', recomms: [ ... ] }
console.log("New Releases:", response[1]);
// New Releases: { recommId: '...', recomms: [ ... ] }
console.log("Popular:", response[2]);
// Popular: { recommId: '...', recomms: [ ... ] }
}
```
The optional parameter `distinctRecomms` of the `Batch` ensures that the recommended items are not repeated across the responses.
You can find more information about Batch requests in the [API Reference](/api/miscellaneous#batch).
### Optional Parameters
Recommendation requests support various optional parameters to customize their behavior. For a comprehensive list, refer to the [API Reference](/api/recommendations). Below is an example showcasing some commonly used parameters:
```
const response = await client.send(new recombee.RecommendItemsToUser('user-13434', 5,
{
// Scenarios help identify the context where recommendations are displayed
// and can be customized in the Admin UI at https://admin.recombee.com
scenario: 'homepage',
// Include detailed properties of the recommended items in the response
returnProperties: true,
// Specify which properties to include (requires returnProperties = true)
includedProperties: ['title', 'img_url', 'url', 'price'],
// Apply a ReQL filter to refine recommendations,
// e.g., "Recommend only items with a title that are in stock."
filter: "'title' != null AND 'availability' == \"in stock\""
// Note: You can define scenario-specific filters in the Admin UI.
}
));
```
## Error Handling
The API client throws errors when an error occurs.
The possible errors are:
| Error | Cause |
| ------------------------------ | ------------------------------------------------------- |
| ApiError | Base class for all errors |
| ResponseError extends ApiError | The API returned an error code (e.g. invalid parameter) |
| TimeoutError extends ApiError | Request timed out |
We are doing our best to provide a reliable service, but sometimes things can go wrong. For this reason, we recommend that you always handle exceptions and provide fallbacks in your application.
For example, when requesting recommendations, a fallback could be to display a generic set of items or an error message to the user.
## Integration Example
### 1\. Create a Recombee Account
To follow this example, you'll need a Recombee account. If you don't already have one, you can [sign up for free](https://admin.recombee.com/sign-up).
If you weren't invited to an existing Organization or Database, Recombee will automatically create one for you during registration.
### 2\. Upload the Catalog
The next step is to upload your item catalog to Recombee. You can do this using one of the following methods:
* API-based upload: Follow the instructions in our [Managing Item Catalog guide](/getting_started#getting-started-catalog).
* Catalog Feed: Set up a feed in the [Admin UI](https://admin.recombee.com/).
For this tutorial, we'll use a sample Google Merchant product feed. You can find the sample file at this URL:
```
https://raw.githubusercontent.com/recombee/js-api-client/refs/heads/master/examples/product_feed_sample.xml
```
After adding the feed to the Admin UI and waiting for it to process, you'll be able to see the uploaded items in the Items section of your Database.
### 3\. Integrate Recombee into Your Website
Let's assume we want to show recommendations on the product page of item `product-270` to a user with the ID `user-1539`.
The following code example uses HTML and vanilla JavaScript to send the Detail View interaction of the product by the user and request 3 related items from the Recombee API:
index.html
```
Recombee Integration Example
Related products
```
main.js
```
// A simple function for rendering a box with the recommended product
function showProduct(title, description, link, imageLink, price) {
return [
`
`,
].join('\n');
}
// Initialize client
const client = new recombee.ApiClient(
'js-client-example',
'dXx2Jw4VkkYQP1XU4JwBAqGezs8BNzwhogGIRjDHJi39Yj3i0tWyIZ0IhKKw5Ln7',
{ region: 'eu-west' },
);
const itemId = 'product-270';
const userId = 'user-1539';
// Send Detail View
void client.send(new recombee.AddDetailView(userId, itemId));
try {
// Request recommended items
const response = await client.send(
new recombee.RecommendItemsToItem(itemId, userId, 3, {
returnProperties: true,
includedProperties: ['title', 'description', 'link', 'image_link', 'price'],
filter: "'title' != null AND 'availability' == \"in stock\"",
scenario: 'related_items',
}),
);
// Show recommendations
const recomms_html = response.recomms
.map((r) => r.values)
.map((vals) =>
showProduct(
vals['title'],
vals['description'],
vals['link'],
vals['image_link'],
vals['price'],
),
);
document.getElementById('relatedProducts').innerHTML = recomms_html.join('\n');
} catch (err) {
console.error('Could not load recomms: ', err);
}
```
You should see something like this:
Notice how the properties returned by `returnProperties`, in combination with `includedProperties`, were used to show titles, images, descriptions and URLs.
### Identifying Users Using Google Analytics
In order to achieve personalization, you need a unique identifier for each user.
One of the ways to achieve this can be using Google Analytics. You would need to add the following to the previous example:
index.html
```
```
main.js
```
const client = new recombee.ApiClient(/* ... */);
// Optional check: if you want to ensure gtag is defined
// (this is often not necessary if you define gtag in HTML as shown)
if (typeof gtag !== 'function') {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
}
// Initialize GA4
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX'); // Replace with your GA4 measurement ID
gtag('get', 'G-XXXXXXXXXX', 'client_id', async (clientId) => {
void client.send(new recombee.AddDetailView(clientId, itemId));
try {
const response = await client.send(
new recombee.RecommendItemsToUser(clientId, 3, {
returnProperties: true,
includedProperties: ['title', 'description', 'link', 'image_link', 'price'],
filter: "'title' != null AND 'availability' == \"in stock\"",
scenario: 'homepage',
}),
);
const recomms = response.recomms;
// ...
} catch (error) {
// Handle errors
}
});
```
This example uses the [Recommend Items to User](/api/recommendations#recommend-items-to-user) API endpoint. You can use this recommendation type in various places, such as on your homepage.
---
# Kotlin API Client
> Source: https://docs.recombee.com/kotlin_client
> For the complete documentation index, see [llms.txt](/llms.txt).
# Kotlin API Client
This library allows you to request recommendations and send interactions between users and items (such as views, bookmarks, or purchases) to Recombee. It is a thin wrapper around the [Recombee API](/api) and provides a simple way to interact with it.
Client-side SDK
This SDK is designed for usage in Android applications or other client-side applications (e.g. Compose Multiplatform).
For server-side integration with the Recombee API, use our dedicated [Java library](https://github.com/recombee/java-api-client)or other available [server-side SDKs](/api_clients#server-side).
For security reasons, it is not possible to change the item catalog, such as the properties of items, using this SDK. To send your Catalog to Recombee, use one of the following methods:
* Use one of our server-side SDKs, for example using a script which runs periodically (see [Managing Item Catalog](/getting_started#getting-started-catalog) for more details),
* Or set up a [Catalog Feed](/catalog_feeds) in the [Admin UI](https://admin.recombee.com/).
[GitHub: See the implementation, contribute, or report issues](https://github.com/Recombee/kotlin-api-client)[API Reference: List of all available endpoints with examples](/api)
## Install
The client is available in the [Maven Central Repository](https://mvnrepository.com/artifact/com.recombee/apiclientkotlin/), which [is included](https://developer.android.com/build/remote-repositories) in new Android projects by default.
Adding the client into your project is therefore as simple as adding the dependency into your `build.gradle`:
```kotlindsl
dependencies {
implementation("com.recombee:apiclientkotlin:6.2.1")
}
```
You can then find all the classes and methods in the `com.recombee.apiclientkotlin` package and its subpackages.
## Configure
In order to use the API, you will need to create an instance of the `RecombeeClient` class. You will need:
* the **ID of your database**,
* the **public token**.
You can find these in the Admin UI, in [your Database's Settings page](https://admin.recombee.com/go-to-database/settings), under **API ID & Tokens**. Along with this information, you can also find the full code snippet for initializing the client, including the above-mentioned parameters.
Ideally, you should only have one instance of the `RecombeeClient` in your application, as it is a lightweight object and can be reused for multiple requests.
Tip
We published a simple [Android example app](https://github.com/recombee/android-demo) to help you with the integration. Feel free to use it as a reference.
You can initialize the client as follows:
```
import com.recombee.apiclientkotlin.RecombeeClient
import com.recombee.apiclientkotlin.util.Region
// Initialize the API client with the ID of your database and the associated PUBLIC token
val client = RecombeeClient(
databaseId = "database-id",
publicToken = "...db-public-token...",
region = Region.UsWest // the region of your database
)
```
You can also set several optional parameters when initializing the client:
```
val client = RecombeeClient(
// Required parameters:
databaseId = "database-id",
publicToken = "...db-public-token...",
// Optional parameters:
// Use this if you were assigned a custom URI by the Recombee Support team (default: null)
baseUri = "custom-uri.recombee.com",
// The port to connect to (default: null)
port = 443,
// Whether to use HTTPS - can be used for debugging (default: true)
useHttpsByDefault = true,
)
```
## Send Interactions
After you have initialized the client, you can send interactions between users and items.
The individual interactions are classes within the `com.recombee.apiclientkotlin.requests` package. After you create an instance of the interaction, you can send it using one of two methods of the `RecombeeClient` class:
* `send` \- for callbacks
* `sendAsync` \- for coroutines (must be called from inside a `CoroutineScope`)
Each interaction has both mandatory and optional parameters.
The most important optional parameter is `recommId` \- the ID of the recommendation to which the interaction belongs. Providing this ID allows you to track successful recommendations. For more information, read about [Reported Metrics](/admin_ui#reported-metrics).
For a full list of interactions, along with their parameters, refer to the [API Reference](/api).
```
import com.recombee.apiclientkotlin.requests.*
// Either create the interaction first and then send it
val bookmark = AddBookmark(userId = "user-13434", itemId = "item-256")
client.send(bookmark)
// Or send it directly
client.send(
AddCartAddition(
userId = "user-4395",
itemId = "item-129",
recommId = "23eaa09b-0e24-4487-ba9c-8e255feb01bb",
)
)
client.send(AddDetailView(userId = "user-9318", itemId = "item-108"))
client.send(AddPurchase(userId = "user-7499", itemId = "item-750"))
client.send(AddRating(userId = "user-3967", itemId = "item-365", rating = 0.5))
client.send(SetViewPortion(userId = "user-4289", itemId = "item-487", portion = 0.3))
```
If you want to send multiple interactions at once, you can use the `Batch` request:
```
import com.recombee.apiclientkotlin.requests.*
val batch = Batch(listOf(
AddBookmark(userId = "user-13434", itemId = "item-256"),
AddCartAddition(userId = "user-4395", itemId = "item-129", cascadeCreate = true),
AddDetailView(userId = "user-9318", itemId = "item-108"),
))
client.send(batch)
```
You can then use callbacks (or `Result`) to handle any exceptions that may occur.
```callback
client.send(
AddRating(
userId = "user-3967",
itemId = "item-365",
rating = 0.5,
cascadeCreate = true
),
{ println("Interaction sent successfully") },
{ exception: ApiException ->
println("Exception: $exception")
// use fallback ...
}
)
```
## Get Recommendations
With an initialized client, you can also request recommendations.
There are multiple types of recommendations, such as:
* [Recommend Items to User](/api/recommendations#recommend-items-to-user),
* [Recommend Items to Item](/api/recommendations#recommend-items-to-item),
* [Recommend Item Segments to User](/api/recommendations#recommend-item-segments-to-user) (these can be categories, genres, artists, etc.),
* or [others](/api/recommendations).
Each recommendation request is a class within the `com.recombee.apiclientkotlin.requests` package.
After you create an instance of the recommendation request, you can send it using the `send` or `sendAsync` methods of the client (depending on whether you want to use callbacks or coroutines).
```callback
val request = RecommendItemsToUser(
userId = "user-x",
count = 10,
scenario = "homepage-for-you"
)
client.send(request,
{ recommendationResponse: RecommendationResponse ->
println("recommId: ${recommendationResponse.recommId}")
for (recommendedItem in recommendationResponse.recomms) {
println("ID: ${recommendedItem.id}")
}
},
{ exception: ApiException ->
println("Exception: $exception")
// use fallback ...
}
)
```
For a full list of request parameters and possible responses, visit the [API Reference](/api/recommendations).
### Personalized Search
[Personalized full-text search](/api/search#search-items) is requested in the same way as recommendations:
```callback
val searchQuery = " ... search query from search field ...."
val request = SearchItems(
userId = "user-x",
searchQuery = searchQuery,
count = 10,
scenario = "search",
returnProperties = true
)
client.send(request,
{ searchResponse: SearchResponse ->
println("recommId: ${searchResponse.recommId}")
for (recommendedItem in searchResponse.recomms) {
println("ID: ${recommendedItem.id} Values: ${recommendedItem.getValues()}")
}
},
{ exception: ApiException ->
println("Exception: $exception")
// use fallback ...
}
)
```
### Recommend Next Items
If you are implementing features like infinite scroll or pagination, you can use the `RecommendNextItems` request to load recommendations progressively.
This means you can fetch the next set of recommended items without repeating the ones you have already displayed.
To use this functionality, you must provide the `recommId` from the initial recommendation request.
For more details, see the [Recommend Next Items](/api/recommendations#recommend-next-items) documentation.
```
var initialRecommId: String? = null
// Fetch the initial set of 5 recommendations for user-13434
val initialRecomms = client.sendAsync(RecommendItemsToUser("user-1", 5))
initialRecomms.onSuccess { it ->
// Store the recommId to be used by the next request
initialRecommId = it.recommId
// Display recommendations
}
// Get the next 3 recommendations as user-13434 scrolls down
initialRecommId?.let { recommId ->
val nextRecomms = client.sendAsync(RecommendNextItems(recommId, 5))
nextRecomms.onSuccess { TODO() }
}
```
### Batch Requests
You may encounter a situation where you display recommendations in multiple places on your website.
In such cases, you can use the `Batch` request to send multiple recommendation requests at once. This can help reduce the number of HTTP requests and improve performance.
For example, you can request the most popular items, as well as items related to a specific user or item, in a single Batch:
```
val batch =
Batch(
requests =
listOf(
RecommendItemsToItem(
targetUserId = "user-13434",
itemId = "item-356",
count = 10,
scenario = "because-you-watched",
returnProperties = true,
includedProperties = listOf("title", "images"),
),
RecommendItemsToUser(
userId = "user-13434",
count = 10,
scenario = "new-releases",
returnProperties = true,
includedProperties = listOf("title", "images"),
),
RecommendItemsToUser(
userId = "user-13434",
count = 10,
scenario = "popular",
returnProperties = true,
includedProperties = listOf("title", "images"),
),
),
distinctRecomms = true,
)
val result = client.sendAsync(batch)
if (result.isFailure) {
return listOf()
}
val data = result.getOrElse { listOf() }
val sections: List> =
data.map {
if (!it.successful) listOf()
else {
val response = it.getResponse() as RecommendationResponse
response.recomms.map { item ->
Item(
id = item.id,
title = item.getValues()["title"] as? String ?: "",
images = item.getValues()["images"] as? List ?: listOf(),
recommId = response.recommId,
)
}
}
}
println("Because You Watched: ${sections[0]}")
// Because You Watched: [Item(id=..., title=..., ...), ...]
println("New Releases: ${sections[1]}")
// New Releases: [Item(id=..., title=..., ...), ...]
println("Popular: ${sections[2]}")
// Popular: [Item(id=..., title=..., ...), ...]
```
The optional parameter `distinctRecomms` of the `Batch` ensures that the recommended items are not repeated across the responses.
You can find more information about Batch requests in the [API Reference](/api/miscellaneous#batch).
### Optional Parameters
Recommendation requests support various optional parameters to customize their behavior. For a comprehensive list, refer to the [API Reference](/api/recommendations). Below is an example showcasing some commonly used parameters:
```
val request = RecommendItemsToUser(
userId = "user-13434",
count = 5,
// Scenarios help identify the context where recommendations are displayed
// and can be customized in the Admin UI at https://admin.recombee.com
scenario = "homepage",
// Include detailed properties of the recommended items in the response
returnProperties = true,
// Specify which properties to include (requires returnProperties = true)
includedProperties = listOf("title", "img_url", "url", "price"),
// Apply a ReQL filter to refine recommendations,
// e.g., "Recommend only items with a title that are in stock."
filter = "'title' != null AND 'availability' == \"in stock\""
// Note: You can define scenario-specific filters in the Admin UI.
)
```
## Error Handling
The API client throws exceptions when an error occurs. The exceptions are part of the `com.recombee.apiclientkotlin.exceptions` package.
The possible exceptions are:
| Exception | Cause |
| ------------------------------------ | ------------------------------------------------------- |
| ApiException | Base class for all exceptions |
| ResponseException : ApiException | The API returned an error code (e.g. invalid parameter) |
| ApiIOException : ApiException | Request failed (e.g. network issues) |
| ApiTimeoutException : ApiIOException | Request timed out |
We are doing our best to provide a reliable service, but sometimes things can go wrong. For this reason, we recommend that you always handle exceptions and provide fallbacks in your application.
For example, when requesting recommendations, a fallback could be to display a generic set of items or an error message to the user.
---
# Swift API Client
> Source: https://docs.recombee.com/swift_client
> For the complete documentation index, see [llms.txt](/llms.txt).
# Swift API Client
This library allows you to request recommendations and send interactions between users and items (such as views, bookmarks, or purchases) to Recombee. It is a thin wrapper around the [Recombee API](/api) and provides a simple way to interact with it.
Client-side SDK
This SDK is designed for use in iOS or macOS applications.
For security reasons, it is not possible to change the item catalog, such as the properties of items, using this SDK. To send your Catalog to Recombee, use one of the following methods:
* Use one of our server-side SDKs, for example using a script which runs periodically (see [Managing Item Catalog](/getting_started#getting-started-catalog) for more details),
* Or set up a [Catalog Feed](/catalog_feeds) in the [Admin UI](https://admin.recombee.com/).
[GitHub: See the implementation, contribute, or report issues](https://github.com/Recombee/swift-api-client)[API Reference: List of all available endpoints with examples](/api)
## Install
Add the dependency to your Xcode project using **Swift Package Manager**:
1. In Xcode, go to `File → Add Packages`.
2. Enter the repository URL: `https://github.com/recombee/swift-api-client`.
3. Choose the latest version and confirm.
Alternatively, in `Package.swift`:
```
.package(url: "https://github.com/recombee/swift-api-client", from: "6.2.0")
```
Then add the following to your target dependencies:
```
.target(
name: "MyApp",
dependencies: ["RecombeeClient"]
)
```
## Configure
In order to use the API, you will need to create an instance of the `RecombeeClient` class. You will need:
* the **ID of your database**,
* the **public token**.
You can find these in the Admin UI, in [your Database's Settings page](https://admin.recombee.com/go-to-database/settings), under **API ID & Tokens**. Along with this information, you can also find a complete code snippet for initializing the client.
Ideally, you should only create **one instance** of `RecombeeClient` in your application. It is a lightweight object and can be reused for multiple requests.
Tip
We published a simple [iOS example app](https://github.com/recombee/ios-demo) to help you with the integration. Feel free to use it as a reference.
You can initialize the client as follows:
```
import RecombeeClient
// Initialize the API client with the ID of your database and the associated public token
let client = RecombeeClient(
databaseId: "database-id",
publicToken: "...db-public-token...",
region: .euWest // the region of your database
)
```
You can also configure optional parameters when initializing the client:
```
let client = RecombeeClient(
databaseId: "database-id",
publicToken: "...db-public-token...",
region: .euWest // the region of your database
// Optional parameters:
// Use this if you were assigned a custom URI by the Recombee Support team (default: nil)
baseUri: "custom-uri.recombee.com",
// The port to connect to (default: nil)
port: 443,
// Whether to use HTTPS - can be disabled for debugging (default: true)
useHttpsByDefault: true
)
```
## Send Interactions
After you have initialized the client, you can send interactions between users and items.
The individual interactions are types conforming to the `Request` protocol in the Recombee Swift SDK. You create an instance of the interaction and send it using the `send` method of the `RecombeeClient` class.
Alternatively, when you don't need to process the response, you can use the `sendDetached` method instead, which sends a request to the Recombee API in a detached task with default priority.
```
// Either create the interaction first and then send it
let bookmark = AddBookmark(userId: "user-13434", itemId: "item-256")
try await client.send(bookmark)
// Or send it directly
try await client.send(
AddCartAddition(
userId: "user-4395",
itemId: "item-129",
recommId: "23eaa09b-0e24-4487-ba9c-8e255feb01bb"
)
)
try await client.send(AddDetailView(userId: "user-9318", itemId: "item-108"))
try await client.send(AddPurchase(userId: "user-7499", itemId: "item-750"))
client.sendDetached(AddRating(userId: "user-3967", itemId: "item-365", rating: 0.5))
client.sendDetached(SetViewPortion(userId: "user-4289", itemId: "item-487", portion: 0.3))
```
Each interaction has both mandatory and optional parameters.
The most important optional parameter is `recommId` — if the interaction is based on a previous recommendation, it is the ID of the recommendation request that returned the item.
Providing this ID allows you to track successful recommendations. For more information, read about [Reported Metrics](/admin_ui#reported-metrics).
For a full list of interactions and their parameters, refer to the [API Reference](/api).
You can also send multiple interactions at once using the `Batch` request:
```
let batch = Batch(requests: [
AddBookmark(userId: "user-13434", itemId: "item-256"),
AddCartAddition(userId: "user-4395", itemId: "item-129", cascadeCreate: true),
AddDetailView(userId: "user-9318", itemId: "item-108")
])
let responses = try await client.send(batch)
```
To handle errors gracefully, use `do-catch` blocks:
```
do {
try await client.send(
AddRating(
userId: "user-3967",
itemId: "item-365",
rating: 0.5,
cascadeCreate: true
)
)
print("Interaction sent successfully")
} catch let error as ClientError {
print("ClientError: \(error.localizedDescription)")
} catch {
print("Unexpected error: \(error.localizedDescription)")
}
```
## Get Recommendations
With an initialized client, you can also request recommendations.
There are multiple types of recommendations, such as:
* [Recommend Items to User](/api/recommendations#recommend-items-to-user),
* [Recommend Items to Item](/api/recommendations#recommend-items-to-item),
* [Recommend Item Segments to User](/api/recommendations#recommend-item-segments-to-user) (these can be categories, genres, artists, etc.),
* or [others](/api/recommendations).
Each recommendation request is a struct within the `RecombeeClient` module and is sent using the `send` method.
```
let client = RecombeeClient(
databaseId: "your-database-id",
publicToken: "your-public-token",
region: .usWest
)
do {
let request = RecommendItemsToUser(
userId: "user-x",
count: 10,
scenario: "homepage-for-you"
)
let response = try await client.send(request)
print("recommId: \(response.recommId)")
for item in response.recomms {
print("ID: \(item.id)")
}
} catch {
print("Error: \(error)")
// Provide fallback...
}
```
For a full list of request parameters and possible responses, visit the [API Reference](/api/recommendations).
### Personalized Search
[Personalized full-text search](/api/search#search-items) is requested in the same way as recommendations:
```
let request = SearchItems(
userId: "user-x",
searchQuery: "headphones",
count: 10,
scenario: "search",
returnProperties: true
)
do {
let response = try await client.send(request)
print("recommId: \(response.recommId)")
for item in response.recomms {
print("ID: \(item.id), Values: \(item.values ?? [:])")
}
} catch {
print("Search error: \(error)")
}
```
### Recommend Next Items
If you are implementing features like infinite scroll or pagination, you can use the `RecommendNextItems` request to load recommendations progressively.
This means you can fetch the next set of recommended items without repeating the ones you have already displayed.
To use this functionality, you must provide the `recommId` from the initial recommendation request.
For more details, see the [Recommend Next Items](/api/recommendations#recommend-next-items) documentation.
```
// Fetch initial recommendations
let initial = try await client.send(
RecommendItemsToUser(userId: "user-1", count: 5)
)
let recommId = initial.recommId
// Later (e.g. when scrolling)
let next = try await client.send(
RecommendNextItems(recommId: recommId, count: 5)
)
for item in next.recomms {
print("Next: \(item.id)")
}
```
### Optional Parameters
Recommendation requests support various optional parameters to customize their behavior. For a comprehensive list, refer to the [API Reference](/api/recommendations). Below is an example showcasing some commonly used parameters:
```
let request = RecommendItemsToUser(
userId: "user-13434",
count: 5,
// Scenarios help identify the context where recommendations are displayed
// and can be customized in the Admin UI at https://admin.recombee.com
scenario: "homepage",
// Include detailed properties of the recommended items in the response
returnProperties: true,
// Specify which properties to include (requires returnProperties = true)
includedProperties: ["title", "img_url", "url", "price"],
// Apply a ReQL filter to refine recommendations,
// e.g., "Recommend only items with a title that are in stock."
filter: "'category' == \"chairs\" and 'price' < 200"
// Note: You can define scenario-specific filters in the Admin UI.
// The filter defined here is combined with the Admin UI filter using logical AND.
)
```
### Batch Requests
You may encounter a situation where you display recommendations in multiple places in your app.
In such cases, you can use the `Batch` request to send multiple recommendation requests at once. This can help reduce the number of HTTP requests and improve performance.
For example, you can request the most popular items, as well as items related to a specific user or item, in a single `Batch`:
```
/// A basic representation of a recommended item.
struct Item {
let id: String
let title: String
let images: [String]
let recommId: String
}
let batch = Batch(
requests: [
RecommendItemsToItem(
itemId: "item-356",
targetUserId: "user-13434",
count: 3,
scenario: "because-you-watched",
returnProperties: true,
includedProperties: ["title", "images"]
),
RecommendItemsToUser(
userId: "user-13434",
count: 3,
scenario: "new-releases",
returnProperties: true,
includedProperties: ["title", "images"]
),
RecommendItemsToUser(
userId: "user-13434",
count: 3,
scenario: "popular",
returnProperties: true,
includedProperties: ["title", "images"]
)
],
distinctRecomms: true
)
do {
let responses = try await client.send(batch)
let sections: [[Item]] = responses.map { wrapper in
if let response = try? wrapper.response?.decode(as: RecommendationResponse.self) {
return response.recomms.map { item in
Item(
id: item.id,
title: item.values?["title"] as? String ?? "",
images: item.values?["images"] as? [String] ?? [],
recommId: response.recommId
)
}
} else {
return []
}
}
print("Because You Watched: \(sections[0])")
print("New Releases: \(sections[1])")
print("Popular: \(sections[2])")
} catch {
print("Batch request failed: \(error)")
}
```
The optional parameter `distinctRecomms` of the `Batch` ensures that the recommended items are not repeated across the responses.
You can find more information about Batch requests in the [API Reference](/api/miscellaneous#batch).
## Error Handling
The API client throws errors of type `ClientError` when an operation fails. Each case of this enum represents a different failure scenario that may occur while communicating with the Recombee API.
These errors are part of the `RecombeeClient` SDK and can be used in Swift's `do-catch` error handling blocks.
| Error | Cause |
| ------------------------- | ------------------------------------------------------------------------------------ |
| ClientError.timeout | The request exceeded the configured timeout interval. |
| ClientError.responseError | The API returned a non-success HTTP status code (e.g. 400, 500). |
| ClientError.networkError | A network-related issue occurred, such as a connection failure. |
| ClientError.decodingError | The response could not be decoded, possibly due to mismatched types or invalid data. |
| ClientError.unknownError | An unspecified or unrecognized error occurred. |
### Example
```
do {
let response = try await client.send(RecommendItemsToUser(userId: "user-1", count: 5))
print("Recommended items: \(response.recomms.map(\.id))")
} catch let error as ClientError {
print("ClientError: \(error.errorDescription ?? "Unknown error")")
} catch {
print("Unexpected error: \(error.localizedDescription)")
}
```
We are doing our best to provide a reliable service, but sometimes things can go wrong. For this reason, we recommend that you always handle exceptions and provide fallbacks in your application.
For example, when requesting recommendations, a fallback could be to display a generic set of items or an error message to the user.
---
# Widget SDKs
> Source: https://docs.recombee.com/widget-sdks
> For the complete documentation index, see [llms.txt](/llms.txt).
# Widget SDKs
Recombee Widget SDKs offer pre-built, customizable components designed to help you quickly embed personalized recommendations into your website or application.
Whether you’re looking to highlight trending articles in a carousel, showcase recommended products in a visually appealing grid, power a dynamic feed of relevant content, or deliver instant results via a quick search box, these widgets make it easy to deliver real-time, AI-driven recommendations to your users.
## Supported Environments
Each widget type is available as two separate npm packages:
* **Vanilla JavaScript** \- Can be directly included in any website without requiring a build or compilation step.
* **React** \- Designed for projects using React to render user interfaces.
## Available Widgets
### Carousel
Displays recommendations in a horizontally scrollable carousel format, allowing users to browse through items with ease.
[Carousel (JS): @recombee/carousel-widget-js](/widget-sdks/carousel-widget-js)[Carousel (React): @recombee/carousel-widget-react](/widget-sdks/carousel-widget-react)
### Quick Search
Enables instant, personalized search suggestions as the user types.
[Quick Search (JS): @recombee/quick-search-widget-js](/widget-sdks/quick-search-widget-js)[Quick Search (React): @recombee/quick-search-widget-react](/widget-sdks/quick-search-widget-react)
### Grid
Displays recommended items in a fixed or responsive grid layout.
[Grid (JS): @recombee/grid-widget-js](/widget-sdks/grid-widget-js)[Grid (React): @recombee/grid-widget-react](/widget-sdks/grid-widget-react)
### Feed
Presents an infinite, scrollable list of items, with new recommendations loading automatically as the user scrolls or on click.
[Feed (JS): @recombee/feed-widget-js](/widget-sdks/feed-widget-js)[Feed (React): @recombee/feed-widget-react](/widget-sdks/feed-widget-react)
---
# Carousel Widget (JS)
> Source: https://docs.recombee.com/widget-sdks/carousel-widget-js
> For the complete documentation index, see [llms.txt](/llms.txt).
# Carousel Widget (JS)
> A Vanilla JS widget that displays a horizontal scroll of recommended items, designed to increase engagement through visually appealing item rotation.
Use this library when you want to display a widget without using a transpiler like Babel and without using JSX. This library exports a `htm` HTML factory to assemble custom elements of the widget.
This widget library is version 0.2.27 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/carousel-widget-js@0.2.27` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/carousel-widget-js@0.2.27 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
,
} from "@recombee/carousel-widget-js";
import "@recombee/carousel-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "gap-4 p-6",
: "min-w-[240px] min-h-[260px]",
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
The [addRecommIdQueryParam](#api/addRecommIdQueryParam) utility function is used to append the recommendation ID to the item's URL as the `recombee_recomm_id` query parameter.
This enables you to [report successful (clicked) recommendations back to Recombee](/admin_ui#reported-metrics) for improved tracking and performance optimization.
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is handy to understand how to customize the widget to full potential.
### Setting own classes
```
import {
,
,
,
,
,
} from "@recombee/carousel-widget-js";
import "@recombee/carousel-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
:
"overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white",
: "gap-4 p-6",
: "min-w-[240px] min-h-[260px]",
: () =>
`<${}
classNameDisableBase
className="border-b border-slate-600"
contentWrapperClassName="text-center"
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/CarouselWidgetOptions.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , , } from "@recombee/carousel-widget-js";
import "@recombee/carousel-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "gap-4 p-6",
: "min-h-[290px] w-[200px]",
: () =>
`
`,
});
```
## Overriding Base Classes
Some base styles are always applied to ensure the widget maintains the structural shape of a carousel.
However, these can be disabled or overridden if needed. Use the[CarouselWidgetProps.classNameDisableDefault](#api/CarouselWidgetProps.classNameDisableDefault) and related options to opt out of default styling.
```
import {
,
,
,
,
,
} from "@recombee/carousel-widget-js";
import "@recombee/carousel-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: true,
:
"rb:no-scrollbar flex min-h-[420px] snap-x snap-mandatory content-stretch gap-1 overflow-x-auto p-6",
: true,
:
"min-h-[260px] flex min-w-full flex-grow basis-full snap-center",
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## Composite Recommendations
```
const : = ({ }) => {
return new ("top-from-genre-for-you", , {
: {
: true,
},
});
};
import {
,
,
,
,
,
} from "@recombee/carousel-widget-js";
import "@recombee/carousel-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "gap-4 p-6",
: "min-w-[240px] min-h-[260px]",
: ({ }) => {
return
? `
Because you like ${?.}
`
: null;
},
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## API Reference
const
### CarouselWidget
Carousel Widget initialization function
type
### CarouselWidgetOptions
Carousel Widget configuration options.
#### Properties
##### container
string
CSS Selector to target the element where the widget should be inserted.
---
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialItemsCount
number | undefined
Number of items to load immediately. Adjust to have more items loaded ahead of user scrolling.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### SourceItemComponent
((props: { state: CarouselWidgetState; source?: Recommendation | null | undefined; }) => ReactNode) | undefined
A component rendering a source recommended item when using Composite Scenario.
---
##### ItemComponent
(props: { state: CarouselWidgetState; result?: Recommendation | undefined; }) => ReactNode
A component rendering a single recommended item.
---
##### ArrowComponent
((props: CarouselArrowProps) => ReactNode) | undefined
A component rendering either left or right carousel arrow
---
##### CarouselComponent
((props: DefaultCarouselProps) => ReactNode) | undefined
Component responsible for rendering the widget markup.
Example in which the passed component wraps the default carousel component with additional custom HTML.
```
import React from "react";
import {
,
,
,
} from "@recombee/carousel-widget-js";
({
// ...ommited code...
: () => {
return `
Recommended
<${} ...${} />
`;
},
});
```
This property also allows to fully cutomize the carousel HTML in extreme cases.
```
import React from "react";
import { , } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: () => {
return `
// Use carouselProps.state.items array to loop over items
`;
},
});
```
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
type
### CarouselWidgetProps
Carousel Widget React Component configuration properties
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialItemsCount
number | undefined
Number of items to load immediately. Adjust to have more items loaded ahead of user scrolling.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### SourceItemComponent
((props: { state: CarouselWidgetState; source?: Recommendation | null | undefined; }) => ReactNode) | undefined
A component rendering a source recommended item when using Composite Scenario.
---
##### ItemComponent
(props: { state: CarouselWidgetState; result?: Recommendation | undefined; }) => ReactNode
A component rendering a single recommended item.
---
##### ArrowComponent
((props: CarouselArrowProps) => ReactNode) | undefined
A component rendering either left or right carousel arrow
---
##### CarouselComponent
((props: DefaultCarouselProps) => ReactNode) | undefined
Component responsible for rendering the widget markup.
Example in which the passed component wraps the default carousel component with additional custom HTML.
```
import React from "react";
import {
,
,
,
} from "@recombee/carousel-widget-js";
({
// ...ommited code...
: () => {
return `
Recommended
<${} ...${} />
`;
},
});
```
This property also allows to fully cutomize the carousel HTML in extreme cases.
```
import React from "react";
import { , } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: () => {
return `
// Use carouselProps.state.items array to loop over items
`;
},
});
```
---
class
### CarouselWidgetState
Exposes internal state data of the widget to be used in customizable components
#### Properties
##### wrapperRef
ObservableRef
React ref necessary to control the carousel wrapper element. See[Customization Example](#api/CarouselWidgetProps.CarouselComponent).
---
##### contentRef
ObservableRef
React ref necessary to control the carousel content element. See[Customization Example](#api/CarouselWidgetProps.CarouselComponent).
---
##### items
{ key: string; entity: Recommendation; }\[\]
Array of items to show in the carousel.
---
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
##### leftArrow
ArrowState
Current state of left Carousel arrow
---
##### rightArrow
ArrowState
Current state of right Carousel arrow
---
const
### DefaultCarousel
Default visual component used to render carousel container
interface
### DefaultCarouselProps
Carousel Properties
#### Properties
##### state
CarouselWidgetState
Carousel state.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### SourceItemComponent
((props: { state: CarouselWidgetState; source?: Recommendation | null | undefined; }) => ElementType) | undefined
A component rendering a source recommended item when using Composite Scenario.
---
##### ItemComponent
(props: { state: CarouselWidgetState; result?: Recommendation | undefined; }) => ElementType
A component rendering a single recommended item.
---
##### ArrowComponent
((props: CarouselArrowProps) => ElementType) | undefined
A component rendering either left or right carousel arrow
---
const
### DefaultCarouselArrow
Default Carousel arrow component
type
### CarouselArrowProps
Carousel Arrow configuration options
#### Properties
##### arrowDirection
"left" | "right"
The direction of an arrow to render.
---
##### state
CarouselWidgetState
Carousel state.
---
---
# Carousel Widget (React)
> Source: https://docs.recombee.com/widget-sdks/carousel-widget-react
> For the complete documentation index, see [llms.txt](/llms.txt).
# Carousel Widget (React)
> A React component widget that displays a horizontal scroll of recommended items, designed to increase engagement through visually appealing item rotation.
Use this library when you want to render a widget and you are using React and JSX in your project.
This widget library is version 0.2.25 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/carousel-widget-react@0.2.25` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/carousel-widget-react@0.2.25 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="gap-4 p-6"
="min-w-[240px] min-h-[260px]"
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
);
};
```
The [addRecommIdQueryParam](#api/addRecommIdQueryParam) utility function is used to append the recommendation ID to the item's URL as the `recombee_recomm_id` query parameter.
This enables you to [report successful (clicked) recommendations back to Recombee](/admin_ui#reported-metrics) for improved tracking and performance optimization.
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is handy to understand how to customize the widget to full potential.
### Setting own classes
```
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white"
="gap-4 p-6"
="min-w-[240px] min-h-[260px]"
={() => (
<
="border-b border-slate-600"
="text-center"
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
);
};
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/CarouselWidgetProps.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , } from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="gap-4 p-6"
="min-h-[290px] w-[200px]"
={() => (
< ="overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white">
< ="relative overflow-hidden bg-cover bg-no-repeat">
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
{.?.?.["genres"]?.includes("drama") && (
< ="absolute top-3 left-3 bg-[#3f91ff] px-2 text-xs/[1.67] font-semibold text-white">
Drama
>
)}
{.?.?.["genres"]?.includes("science_fiction") && (
< ="absolute top-3 left-3 bg-[#36c696] px-2 text-xs/[1.67] font-semibold text-white">
Sci-Fi
>
)}
>
< ="p-3">
< ="mb-1 line-clamp-4 overflow-hidden text-[14px]/[1.43] text-nowrap text-ellipsis text-[#80868f]">
{`${.?.?.genres?.join(", ")}`}
>
< ="text-md mb-1 overflow-hidden text-nowrap text-ellipsis">
{`${.?.?.title}`}
>
< ="line-clamp-4 pb-3 text-base text-[#3f91ff]">
{`${.?.?.year}`}
>
< ="w-full rounded-lg border border-[#ededed] py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]">
Play
>
>
>
)}
/>
);
};
```
### Custom Arrows
```
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="gap-4 p-6"
="min-h-[400px] w-[400px]"
={() => {
if (
. === "left" &&
...
) {
return (
<
="absolute top-1/2 left-4 -translate-y-6 rounded-lg rounded-sm border border-[#ededed] bg-white px-3 py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]"
="button"
={...}
>
prev
>
);
}
if (
. === "right" &&
...
) {
return (
<
="absolute top-1/2 right-4 -translate-y-6 rounded-lg rounded-sm border border-[#ededed] bg-white px-3 py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]"
="button"
={...}
>
next
>
);
}
}}
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
);
};
```
### Full Customization
```
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => (
<
={}
={}
={() => null}
={() => (
< ="p-4">
<
{...}
="gap-1"
="min-h-[240px] w-[200px]"
/>
< ="flex justify-end gap-2 pt-4">
< ="flex gap-2">
<
={!...}
={...}
>
PREV
>
<
={!...}
={...}
>
NEXT
>
>
>
>
)}
={() => (
< ="overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white">
< ="relative overflow-hidden bg-cover bg-no-repeat">
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
{.?.?.["genres"]?.includes("drama") && (
< ="absolute top-3 left-3 bg-[#3f91ff] px-2 text-xs/[1.67] font-semibold text-white">
Drama
>
)}
{.?.?.["genres"]?.includes("science_fiction") && (
< ="absolute top-3 left-3 bg-[#36c696] px-2 text-xs/[1.67] font-semibold text-white">
Sci-Fi
>
)}
>
< ="p-3">
< ="mb-1 line-clamp-4 overflow-hidden text-[14px]/[1.43] text-nowrap text-ellipsis text-[#80868f]">
{`${.?.?.genres?.join(", ")}`}
>
< ="text-md mb-1 overflow-hidden text-nowrap text-ellipsis">
{`${.?.?.title}`}
>
< ="line-clamp-4 pb-3 text-base text-[#3f91ff]">
{`${.?.?.year}`}
>
< ="w-full rounded-lg border border-[#ededed] py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]">
Play
>
>
>
)}
/>
);
function (: any) {
const = `w-full rounded-lg border border-[#ededed] py-2 px-3 text-center text-[14px]/[1.43] font-medium text-[#80868f]`;
return (
<
={(, {
"opacity-50": .disabled,
})}
{...}
/>
);
}
```
## Overriding Base Classes
Some base styles are always applied to ensure the widget maintains the structural shape of a carousel.
However, these can be disabled or overridden if needed. Use the[CarouselWidgetProps.classNameDisableDefault](#api/CarouselWidgetProps.classNameDisableDefault) and related options to opt out of default styling.
```
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
< ="flex justify-center">
< ="w-[40%]">
<
={}
={}
="rb:no-scrollbar flex min-h-[420px] snap-x snap-mandatory content-stretch gap-1 overflow-x-auto p-6"
="min-h-[260px] flex min-w-full flex-grow basis-full snap-center"
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
>
>
);
};
```
## Composite Recommendations
Widget SDKs can also be used to render [Composite Recommendations](/scenarios/composite-recommendations). A common use case is displaying [dynamic category- or genre-based rails](/scenarios/composite-recommendations#fully-personalized-homepage) on the homepage, as well as scenarios such as [Because You Watched](/scenarios/composite-recommendations#because-you-watched-movie-). The CompositeRecommendation request is called from within the[createRequest](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.createRequest)function. To render the header (for example, the user’s favorite category or the title of the watched movie), implement the[SourceItemComponent](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.SourceItemComponent).
```
const : = ({ }) => {
return new ("top-from-genre-for-you", , {
: { : true },
});
};
import {
,
,
,
,
} from "@recombee/carousel-widget-react";
import "@recombee/carousel-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="gap-4 p-6"
="min-w-[240px] min-h-[260px]"
={({ }) => {
return ? (
< ="px-6">
< ="mt-5 mb-0">Because you like {?.}>
>
) : null;
}}
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
);
};
```
## API Reference
const
### CarouselWidget
Carousel widget React Component. See [CarouselWidgetProps](#api/CarouselWidgetProps) for configuration options.
type
### CarouselWidgetProps
Carousel Widget React Component configuration properties
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-react";
<
// ...ommited code...
={({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
}}
/>;
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialItemsCount
number | undefined
Number of items to load immediately. Adjust to have more items loaded ahead of user scrolling.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### SourceItemComponent
((props: { state: CarouselWidgetState; source?: Recommendation | null | undefined; }) => ReactNode) | undefined
A component rendering a source recommended item when using Composite Scenario.
---
##### ItemComponent
(props: { state: CarouselWidgetState; result?: Recommendation | undefined; }) => ReactNode
A component rendering a single recommended item.
---
##### ArrowComponent
((props: CarouselArrowProps) => ReactNode) | undefined
A component rendering either left or right carousel arrow
---
##### CarouselComponent
((props: DefaultCarouselProps) => ReactNode) | undefined
Component responsible for rendering the widget markup.
Example in which the passed component wraps the default carousel component with additional custom HTML.
```
import React from "react";
import {
,
,
} from "@recombee/carousel-widget-react";
<
// ...ommited code...
={() => {
return (
<>
<>Recommended>
< {...} />
>
);
}}
/>;
```
This property also allows to fully cutomize the carousel HTML in extreme cases.
```
import React from "react";
import { } from "@recombee/carousel-widget-react";
<
// ...ommited code...
={() => {
return (
< ={...}>
<>Recommended>
< ={...}>
// Use carouselProps.state.items array to loop over items
>
>
);
}}
/>;
```
---
class
### CarouselWidgetState
Exposes internal state data of the widget to be used in customizable components
#### Properties
##### wrapperRef
ObservableRef
React ref necessary to control the carousel wrapper element. See[Customization Example](#api/CarouselWidgetProps.CarouselComponent).
---
##### contentRef
ObservableRef
React ref necessary to control the carousel content element. See[Customization Example](#api/CarouselWidgetProps.CarouselComponent).
---
##### items
{ key: string; entity: Recommendation; }\[\]
Array of items to show in the carousel.
---
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
##### leftArrow
ArrowState
Current state of left Carousel arrow
---
##### rightArrow
ArrowState
Current state of right Carousel arrow
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
const
### DefaultCarousel
Default visual component used to render carousel container
interface
### DefaultCarouselProps
Carousel Properties
#### Properties
##### state
CarouselWidgetState
Carousel state.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### SourceItemComponent
((props: { state: CarouselWidgetState; source?: Recommendation | null | undefined; }) => ElementType) | undefined
A component rendering a source recommended item when using Composite Scenario.
---
##### ItemComponent
(props: { state: CarouselWidgetState; result?: Recommendation | undefined; }) => ElementType
A component rendering a single recommended item.
---
##### ArrowComponent
((props: CarouselArrowProps) => ElementType) | undefined
A component rendering either left or right carousel arrow
---
const
### DefaultCarouselArrow
Default Carousel arrow component
type
### CarouselArrowProps
Carousel Arrow configuration options
#### Properties
##### arrowDirection
"left" | "right"
The direction of an arrow to render.
---
##### state
CarouselWidgetState
Carousel state.
---
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
---
# Feed Widget (JS)
> Source: https://docs.recombee.com/widget-sdks/feed-widget-js
> For the complete documentation index, see [llms.txt](/llms.txt).
# Feed Widget (JS)
> A Vanilla JS widget that creates a personalized, scrollable feed of item recommendations, designed for continuous content discovery.
Use this library when you want to display a widget without using a transpiler like Babel and without using JSX. This library exports a `htm` HTML factory to assemble custom elements of the widget.
This widget library is version 0.2.25 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/feed-widget-js@0.2.25` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/feed-widget-js@0.2.25 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
,
} from "@recombee/feed-widget-js";
import "@recombee/feed-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "click",
: 1,
: 2,
: "min-h-[260px]",
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
: () =>
`
`,
});
```
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is especially handy for understanding how to customize the widget to its full potential.
### Setting own classes
```
import {
,
,
,
,
,
} from "@recombee/feed-widget-js";
import "@recombee/feed-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "click",
:
"grid-cols-[repeat(auto-fill,minmax(200px,1fr))] p-3 gap-2 overflow-hidden text-[#282b30] rounded-lg bg-white border border-[#ededed] dark:border-none dark:bg-transparent dark:text-white",
: "min-h-[260px]",
: () =>
`<${}
className="border-b border-slate-600"
contentWrapperClassName="text-center"
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
: () =>
`
`,
});
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/FeedWidgetOptions.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , , } from "@recombee/feed-widget-js";
import "@recombee/feed-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "click",
: "min-h-[310px]",
: () =>
`
`,
});
```
## Overriding Base Classes
Some base styles are always applied to ensure the widget maintains the structural shape of a feed.
However, these can be disabled or overridden if needed. Use the[FeedWidgetProps.classNameDisableDefault](#api/FeedWidgetProps.classNameDisableDefault) and related options to opt out of default styling.
```
import {
,
,
,
,
,
} from "@recombee/feed-widget-js";
import "@recombee/feed-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "click",
: 2,
: "min-h-[260px]",
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
: () =>
`
`,
});
```
## API Reference
const
### FeedWidget
Feed widget initialization function. See [FeedWidgetOptions](#api/FeedWidgetOptions)
type
### FeedWidgetOptions
Configuration options of Feed widget
#### Properties
##### container
string
CSS Selector to target the element where the widget should be inserted.
---
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialRowsCount
number | undefined
Number of rows to load initially.
---
##### loadMoreRowsCount
number | undefined
Number of rows to load on "load more" trigger invocation.
---
##### loadMoreTrigger
"scroll" | "click"
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: FeedWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### LoadMoreTriggerComponent
FC<{ state: FeedWidgetState; }> | (FC<{ state: FeedWidgetState; }> & FC<{ state: FeedWidgetState; }>) | undefined
---
##### SourceItemComponent
FC<{ state: FeedWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
type
### FeedWidgetProps
Configuration options for the Feed widget.
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialRowsCount
number | undefined
Number of rows to load initially.
---
##### loadMoreRowsCount
number | undefined
Number of rows to load on "load more" trigger invocation.
---
##### loadMoreTrigger
"scroll" | "click"
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: FeedWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### LoadMoreTriggerComponent
FC<{ state: FeedWidgetState; }> | (FC<{ state: FeedWidgetState; }> & FC<{ state: FeedWidgetState; }>) | undefined
---
##### SourceItemComponent
FC<{ state: FeedWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
class
### FeedWidgetState
A Class exposing Feed internal state to be used for customization.
#### Properties
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### items
({ type: "ENTITY"; key: string; entity: Recommendation; } | { type: "PLACEHOLDER"; key: string; })\[\]
Array of items to show in the feed
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
##### handleTriggerClick
() => void
Handles clicking on a trigger to load more feed items by a configured increment
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
---
# Feed Widget (React)
> Source: https://docs.recombee.com/widget-sdks/feed-widget-react
> For the complete documentation index, see [llms.txt](/llms.txt).
# Feed Widget (React)
> A React component widget that creates a personalized, scrollable feed of item recommendations, designed for continuous content discovery.
Use this library when you want to render a widget and you are using React and JSX in your project.
This widget library is version 0.2.23 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/feed-widget-react@0.2.23` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/feed-widget-react@0.2.23 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
} from "@recombee/feed-widget-react";
import "@recombee/feed-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="click"
={1}
={2}
="min-h-[260px]"
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
={() => (
< ="flex justify-center p-2">
<
="me-2 mb-2 rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
={..}
>
More
>
>
)}
/>
);
};
```
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is especially handy for understanding how to customize the widget to its full potential.
### Setting own classes
```
import {
,
,
,
,
} from "@recombee/feed-widget-react";
import "@recombee/feed-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="click"
="grid-cols-[repeat(auto-fill,minmax(200px,1fr))] p-3 gap-2 overflow-hidden text-[#282b30] rounded-lg bg-white border border-[#ededed] dark:border-none dark:bg-transparent dark:text-white"
="min-h-[260px]"
={() => (
<
="border-b border-slate-600"
="text-center"
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
={() => (
< ="flex justify-center p-2">
<
="me-2 mb-2 rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
={..}
>
More
>
>
)}
/>
);
};
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/FeedWidgetProps.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , } from "@recombee/feed-widget-react";
import "@recombee/feed-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="click"
="min-h-[310px]"
={() => (
< ="overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white">
< ="relative overflow-hidden bg-cover bg-no-repeat">
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
{.?.?.["genres"]?.includes("drama") && (
< ="absolute top-3 left-3 bg-[#3f91ff] px-2 text-xs/[1.67] font-semibold text-white">
Drama
>
)}
{.?.?.["genres"]?.includes("science_fiction") && (
< ="absolute top-3 left-3 bg-[#36c696] px-2 text-xs/[1.67] font-semibold text-white">
Sci-Fi
>
)}
>
< ="p-3">
< ="mb-1 line-clamp-4 overflow-hidden text-[14px]/[1.43] text-nowrap text-ellipsis text-[#80868f]">
{`${.?.?.genres?.join(", ")}`}
>
< ="text-md mb-1 overflow-hidden text-nowrap text-ellipsis">
{`${.?.?.title}`}
>
< ="line-clamp-4 pb-3 text-base text-[#3f91ff]">
{`${.?.?.year}`}
>
< ="w-full rounded-lg border border-[#ededed] py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]">
Play
>
>
>
)}
={() => (
< ="flex justify-center p-2">
<
="me-2 mb-2 rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
={..}
>
More
>
>
)}
/>
);
};
```
## Overriding Base Classes
Some base styles are always applied to ensure the widget maintains the structural shape of a feed.
However, these can be disabled or overridden if needed. Use the[FeedWidgetProps.classNameDisableDefault](#api/FeedWidgetProps.classNameDisableDefault) and related options to opt out of default styling.
```
import {
,
,
,
,
} from "@recombee/feed-widget-react";
import "@recombee/feed-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="click"
={2}
="min-h-[260px]"
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
={() => (
< ="flex justify-center p-2">
<
="me-2 mb-2 rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
={..}
>
More
>
>
)}
/>
);
};
```
## Composite Recommendations
Widget SDKs can also be used to render [Composite Recommendations](/scenarios/composite-recommendations). A common use case is displaying [dynamic category- or genre-based rails](/scenarios/composite-recommendations#fully-personalized-homepage) on the homepage, as well as scenarios such as [Because You Watched](/scenarios/composite-recommendations#because-you-watched-movie-). The CompositeRecommendation request is called from within the[createRequest](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.createRequest)function. To render the header (for example, the user’s favorite category or the title of the watched movie), implement the[SourceItemComponent](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.SourceItemComponent).
```
const : = ({ }) => {
return new ("top-from-genre-for-you", , {
: { : true },
});
};
import {
,
,
,
,
} from "@recombee/feed-widget-react";
import "@recombee/feed-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="click"
={1}
={2}
="min-h-[260px]"
={({ }) => {
return ? (
< ="my-5">Because you like {?.}>
) : null;
}}
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
={() => (
< ="flex justify-center p-2">
<
="me-2 mb-2 rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
={..}
>
More
>
>
)}
/>
);
};
```
## API Reference
const
### FeedWidget
Feed widget component. See [FeedWidgetProps](#api/FeedWidgetProps) for configuration options.
type
### FeedWidgetProps
Configuration options for the Feed widget.
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-react";
<
// ...ommited code...
={({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
}}
/>;
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### initialRowsCount
number | undefined
Number of rows to load initially.
---
##### loadMoreRowsCount
number | undefined
Number of rows to load on "load more" trigger invocation.
---
##### loadMoreTrigger
"scroll" | "click"
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: FeedWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### LoadMoreTriggerComponent
FC<{ state: FeedWidgetState; }> | (FC<{ state: FeedWidgetState; }> & FC<{ state: FeedWidgetState; }>) | undefined
---
##### SourceItemComponent
FC<{ state: FeedWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
class
### FeedWidgetState
A Class exposing Feed internal state to be used for customization.
#### Properties
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### items
({ type: "ENTITY"; key: string; entity: Recommendation; } | { type: "PLACEHOLDER"; key: string; })\[\]
Array of items to show in the feed
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
##### handleTriggerClick
() => void
Handles clicking on a trigger to load more feed items by a configured increment
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
---
# Grid Widget (JS)
> Source: https://docs.recombee.com/widget-sdks/grid-widget-js
> For the complete documentation index, see [llms.txt](/llms.txt).
# Grid Widget (JS)
> A Vanilla JS widget that renders a grid of recommended items, optimized for high-density product presentation.
Use this library when you want to display a widget without using a transpiler like Babel and without using JSX. This library exports a `htm` HTML factory to assemble custom elements of the widget.
This widget library is version 0.2.25 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/grid-widget-js@0.2.25` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/grid-widget-js@0.2.25 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
Number of items loaded to grid widget is governed by CSS Grid styling which must be provided. See the example code where the grid is defined using utility classes provided by TailwindCSS.
```
import {
,
,
,
,
,
} from "@recombee/grid-widget-js";
import "@recombee/grid-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
:
"grid-cols-[repeat(1,1fr)] grid-rows-[repeat(4,1fr)] gap-2 @lg:grid-cols-[repeat(2,1fr)] @lg:grid-rows-[repeat(3,1fr)] @xl:grid-cols-[repeat(4,1fr)] @xl:grid-rows-[repeat(2,1fr)]",
: "min-h-[260px]",
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is especially handy for understanding how to customize the widget to its full potential.
### Setting own classes
```
import {
,
,
,
,
,
} from "@recombee/grid-widget-js";
import "@recombee/grid-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
:
"rb:overflow-hidden rb:text-[#282b30] rb:rounded-lg rb:bg-white rb:border rb:border-[#ededed] rb:dark:border-none rb:dark:bg-transparent rb:dark:text-white",
:
"grid-cols-[repeat(4,1fr)] grid-rows-[repeat(1,1fr)] gap-2 p-1",
: "min-h-[260px]",
: () =>
`<${}
className="border-b border-slate-600"
contentWrapperClassName="text-center"
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/GridWidgetOptions.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , , } from "@recombee/grid-widget-js";
import "@recombee/grid-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: "min-h-[310px]",
: () =>
`
`
: null;
},
: () =>
`<${}
href=${(
.?.?.link,
..,
)}
image=${`<${}
src=${`${.?.?.images?.[0]}`}
width=${600}
height=${400}
/>`}
labelContent=${`${.?.?.genres?.join(", ")}`}
title=${`${.?.?.title}`}
highlightedContent=${`${.?.?.year}`}
/>`,
});
```
## API Reference
const
### GridWidget
Grid widget
type
### GridWidgetOptions
Grid widget options
#### Properties
##### container
string
CSS Selector to target the element where the widget should be inserted.
---
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: GridWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### SourceItemComponent
FC<{ state: GridWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
type
### GridWidgetProps
Grid Widget component configuration options
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: GridWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### SourceItemComponent
FC<{ state: GridWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
class
### GridWidgetState
Class exposing internal state of the grid
#### Properties
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### items
({ type: "ENTITY"; key: string; entity: Recommendation; } | { type: "PLACEHOLDER"; key: string; })\[\]
Recommended items to display
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
---
# Grid Widget (React)
> Source: https://docs.recombee.com/widget-sdks/grid-widget-react
> For the complete documentation index, see [llms.txt](/llms.txt).
# Grid Widget (React)
> A React component widget that renders a grid of recommended items, optimized for high-density product presentation.
Use this library when you want to render a widget and you are using React and JSX in your project.
This widget library is version 0.2.23 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/grid-widget-react@0.2.23` and `recombee-js-api-client`packages using your preferred NPM package manager. This example is using`pnpm`.
```
pnpm add @recombee/grid-widget-react@0.2.23 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Please ensure that you provide the user ID (typically obtained from your existing user tracking system), along with other relevant parameters - such as an item ID or [Item Segment](/segmentations) ID - depending on the specific type of recommendation request. See the[Providing User ID](#providing-user-id) section for details on how to obtain user ID in specific cases.
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
const : = ({ }) => {
const = "recommend-items-to-user";
return new (userId, , {
: ,
: true,
: true,
});
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/carousel-widget-react";
import { } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
const = "recommend-items-to-user";
return new (, , {
: ,
: true,
: true,
});
};
```
## Basic Example
The widget in this example uses the [DefaultItem](#api/DefaultItem) component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
Number of items loaded to grid widget is governed by CSS Grid styling which must be provided. See the example code where the grid is defined using utility classes provided by TailwindCSS.
```
import {
,
,
,
,
} from "@recombee/grid-widget-react";
import "@recombee/grid-widget-react/dist/styles.css";
export default () => {
return (
< ="@container">
<
={}
={}
="grid-cols-[repeat(1,1fr)] grid-rows-[repeat(4,1fr)] gap-2 @lg:grid-cols-[repeat(2,1fr)] @lg:grid-rows-[repeat(3,1fr)] @xl:grid-cols-[repeat(4,1fr)] @xl:grid-rows-[repeat(2,1fr)]"
="min-h-[260px]"
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
>
);
};
```
## Custom CSS
Recombee Widgets are designed to be styling-agnostic. You can fully customize their appearance using your own CSS by passing class names through customization properties.
In these docs examples, we use utility classes from [Tailwind CSS](https://tailwindcss.com/) for styling.
Class names for internal elements and custom components are passed as props and applied by the widget during rendering. The default structure of the_Basic Example_ widget is illustrated below (pseudo-code):
```
... more items ...
```
This is especially handy for understanding how to customize the widget to its full potential.
### Setting own classes
```
import {
,
,
,
,
} from "@recombee/grid-widget-react";
import "@recombee/grid-widget-react/dist/styles.css";
export default () => {
return (
< ="@container">
<
={}
={}
="rb:overflow-hidden rb:text-[#282b30] rb:rounded-lg rb:bg-white rb:border rb:border-[#ededed] rb:dark:border-none rb:dark:bg-transparent rb:dark:text-white"
="grid-cols-[repeat(4,1fr)] grid-rows-[repeat(1,1fr)] gap-2 p-1"
="min-h-[260px]"
={() => (
<
="border-b border-slate-600"
="text-center"
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
>
);
};
```
## Custom Templates
Recombee Widgets support full customization of internal components such as the appearance of the recommended items.
You can provide your own components via props like [ItemComponent](#api/GridWidgetProps.ItemComponent) to control the structure, styling, and behavior of the widget.
This flexibility allows you to adapt the widget's appearance and functionality to match your design and user experience requirements.
### Custom Item
```
import { , } from "@recombee/grid-widget-react";
import "@recombee/grid-widget-react/dist/styles.css";
export default () => {
return (
<
={}
={}
="min-h-[310px]"
={() => (
< ="overflow-hidden rounded-lg border-[#ededed] bg-white text-[#282b30] dark:border-none dark:bg-transparent dark:text-white">
< ="relative overflow-hidden bg-cover bg-no-repeat">
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
{.?.?.["genres"]?.includes("drama") && (
< ="absolute top-3 left-3 bg-[#3f91ff] px-2 text-xs/[1.67] font-semibold text-white">
Drama
>
)}
{.?.?.["genres"]?.includes("science_fiction") && (
< ="absolute top-3 left-3 bg-[#36c696] px-2 text-xs/[1.67] font-semibold text-white">
Sci-Fi
>
)}
>
< ="p-3">
< ="mb-1 line-clamp-4 overflow-hidden text-[14px]/[1.43] text-nowrap text-ellipsis text-[#80868f]">
{`${.?.?.genres?.join(", ")}`}
>
< ="text-md mb-1 overflow-hidden text-nowrap text-ellipsis">
{`${.?.?.title}`}
>
< ="line-clamp-4 pb-3 text-base text-[#3f91ff]">
{`${.?.?.year}`}
>
< ="w-full rounded-lg border border-[#ededed] py-2 text-center text-[14px]/[1.43] font-medium text-[#80868f]">
Play
>
>
>
)}
/>
);
};
```
## Composite Recommendations
Widget SDKs can also be used to render [Composite Recommendations](/scenarios/composite-recommendations). A common use case is displaying [dynamic category- or genre-based rails](/scenarios/composite-recommendations#fully-personalized-homepage) on the homepage, as well as scenarios such as [Because You Watched](/scenarios/composite-recommendations#because-you-watched-movie-). The CompositeRecommendation request is called from within the[createRequest](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.createRequest)function. To render the header (for example, the user’s favorite category or the title of the watched movie), implement the[SourceItemComponent](/widget-sdks/carousel-widget-react#api/CarouselWidgetProps.SourceItemComponent).
```
import {
,
,
,
,
} from "@recombee/grid-widget-react";
import "@recombee/grid-widget-react/dist/styles.css";
const : = ({ }) => {
return new ("top-from-genre-for-you", , {
: { : true },
});
};
export default () => {
return (
<
={}
={}
="composite"
="min-h-[310px]"
={({ }) => {
return ? (
< ="my-5">Because you like {?.}>
) : null;
}}
={() => (
<
={(
.?.?.link,
..,
)}
={
<
={`${.?.?.images?.[0]}`}
={600}
={400}
/>
}
={`${.?.?.genres?.join(", ")}`}
={`${.?.?.title}`}
={`${.?.?.year}`}
/>
)}
/>
);
};
```
## API Reference
const
### GridWidget
Grid Widget component
type
### GridWidgetProps
Grid Widget component configuration options
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
CreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-react";
<
// ...ommited code...
={({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
}}
/>;
```
---
##### deduplicationPartitionKey
string | undefined
A string key specifying a group of widgets, in which recommendation results will be deduplicated. By default, all widgets belong to a single group so all results from the same database are deduplicated.
---
##### className
string | undefined
Custom classes of widget wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableDefault
boolean | undefined
Disables default classes of widget wrapper element.
There are some default class names with essential styles applied to the widget wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentClassName
string | undefined
Custom classes of content wrapper element. See[Custom CSS](#custom-css).
---
##### contentClassNameDisableDefault
boolean | "layout" | undefined
Disables default classes of content wrapper element.
There are some default class names with essential styles applied to the content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### itemWrapperClassName
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### itemWrapperClassNameDisableDefault
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### ItemComponent
FC<{ state: GridWidgetState; result: Recommendation; }>
A component rendering a single recommended item.
---
##### SourceItemComponent
FC<{ state: GridWidgetState; source?: Recommendation | null | undefined; }> | undefined
A component rendering a source recommended item when using Composite Scenario.
---
class
### GridWidgetState
Class exposing internal state of the grid
#### Properties
##### sourceItem
Recommendation | null | undefined
Array of items to show in the carousel.
---
##### items
({ type: "ENTITY"; key: string; entity: Recommendation; } | { type: "PLACEHOLDER"; key: string; })\[\]
Recommended items to display
---
##### recommId
string | undefined
Id of recommendation response from which the items originated.
---
const
### DefaultItem
Default Item component provided for basic usage.
interface
### DefaultItemProps
Recommended item component properties.
#### Properties
##### className
string | undefined
Custom classes of item wrapper element. See[Custom CSS](#custom-css).
---
##### classNameDisableBase
boolean | undefined
Disables default classes of item wrapper element.
There are some default class names with essential styles applied to the item wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### imageWrapperClassName
string | undefined
Custom classes of item image wrapper element. See[Custom CSS](#custom-css).
---
##### imageWrapperClassNameDisableBase
boolean | undefined
Disables default classes of item image wrapper element.
There are some default class names with essential styles applied to the item image wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### contentWrapperClassName
string | undefined
Custom classes of item content element. See[Custom CSS](#custom-css).
---
##### result
Recommendation | undefined
A single item recommedation.
---
##### href
string | null | undefined
Item link URL.
---
##### image
ReactNode
Item Image element.
---
##### labelContent
ReactNode
Item content above title. Sets the entire content of an item aside from an image.
---
##### labelContentWrapperClassName
string | undefined
Custom classes of label content wrapper element. See[Custom CSS](#custom-css).
---
##### labelContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of label content wrapper element.
There are some default class names with essential styles applied to the label content wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### title
ReactNode
Item title.
---
##### titleWrapperClassName
string | undefined
Custom classes of title wrapper element. See[Custom CSS](#custom-css).
---
##### titleWrapperClassNameDisableBase
boolean | undefined
Disables default classes of title wrapper element.
There are some default class names with essential styles applied to the title wrapper element. This setting disables them as an escape hatch for customization. See [Custom CSS](#custom-css).
---
##### highlightedContent
ReactNode
Item content under title. Sets the entire content of an item aside from an image.
---
##### highlightedContentWrapperClassName
string | undefined
Custom classes of highlighted content wrapper element. See[Custom CSS](#custom-css).
---
##### highlightedContentWrapperClassNameDisableBase
boolean | undefined
Disables default classes of highlighted content wrapper element.
There are some default class names with essential styles applied to the highlighted content wrapper element. This setting disables them as an escape hatch for customization. See[Custom CSS](#custom-css).
---
##### bottomContent
ReactNode
Any custom content to display at the bottom of the item.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
type
### Recommendation
Single recommendation item
#### Properties
##### id
string
Item ID
---
##### values
{ \[key: string\]: any; } | undefined
Item properties
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
type
### CreateRequestFunction
Factory for creating Recombee API Request to load data into a Widget.
type
### FetchContentOptions
CreateRequestFunction parameter
#### Properties
##### count
number
Number of items to fetch for the widget. Pass it to the appropriate Request constructor.
---
---
# Quick Search Widget (JS)
> Source: https://docs.recombee.com/widget-sdks/quick-search-widget-js
> For the complete documentation index, see [llms.txt](/llms.txt).
# Quick Search Widget (JS)
> A Vanilla JS widget that enables users to perform real-time product searches with instant results, enhancing product discoverability and conversion.
Use this library when you want to display a widget without using a transpiler like Babel and without using JSX. This library exports a `htm` HTML factory to assemble custom elements of the widget.
This widget library is version 0.2.24 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/quick-search-widget-js@0.2.24` and`recombee-js-api-client` packages using your preferred NPM package manager. This example is using `pnpm`.
```
pnpm add @recombee/quick-search-widget-js@0.2.24 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Quick Search widget requires the `createRequest` function to return a Batch Request. For a basic case of single search request, always wrap it in a batch.
```
import { type } from "@recombee/quick-search-widget-react";
import { , , } from "recombee-js-api-client";
const : = ({ }) => {
return new (
[
new (userId, , 5, {
: "search-items",
: true,
: true,
}),
new (userId, , 5, {
: "search-categories",
: true,
}),
],
{
: true,
},
);
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/quick-search-widget-react";
import { , , } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
return new (
[
new (, , 5, {
: "search-items",
: true,
: true,
}),
new (, , 5, {
: "search-categories",
: true,
}),
],
{
: true,
},
);
};
```
## Basic Example
The widget in this example uses the DefaultItem component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
,
,
,
,
} from "@recombee/quick-search-widget-js";
import "@recombee/quick-search-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: 3,
: "(min-width: 1000px)",
: "lg:w-[var(--qs-input-width)] lg:flex lg:justify-center",
: () =>
``,
: () =>
``,
: () =>
`
`,
});
```
## Custom Template
You can customize the appearance and behavior of the Quick Search Widget by overriding its individual components:
* [DropdownComponent](#api/QuickSearchWidgetOptions.DropdownComponent) – Renders the dropdown containing search results.
* [InputComponent](#api/QuickSearchWidgetOptions.InputComponent) – Handles the search input field where users type their queries.
* [TriggerComponent](#api/QuickSearchWidgetOptions.TriggerComponent) – Controls how the widget is opened on mobile devices.
The example also demonstrates how to make the search form submittable to a dedicated results page using a `submit` button.
```
import {
,
,
,
,
,
,
,
} from "@recombee/quick-search-widget-js";
import "@recombee/quick-search-widget-js/dist/styles.css";
({
: "#widget-root",
: ,
: ,
: 3,
: 1000,
: "(min-width: 1000px)",
: () =>
``,
: () =>
``,
: () =>
`
`,
});
```
## API Reference
const
### QuickSearchWidget
Quick Search widget
type
### QuickSearchWidgetOptions
Quick Search widget options
#### Properties
##### container
string
CSS Selector to target the element where the widget should be inserted.
---
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
QuickSearchCreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### initialQuery
string | undefined
String to be prefilled into the search input
---
##### minSearchCharactersCount
number
Minimum length of search query for search request to be sent.
---
##### typingDebounceDuration
number | undefined
Maximum duration between keystrokes in milliseconds before search request is made.
---
##### primaryResultsIndex
number | undefined
Index of request in a batch from which the results are considered to be navigable by arrow keys.
---
##### InputComponent
FC
Component responsible for rendering the widget input.
---
##### TriggerComponent
FC
Component responsible for rendering the widget trigger on mobile devices.
---
##### DropdownComponent
FC
Component responsible for rendering the widget dropdown.
---
##### className
string | undefined
Custom classes of widget wrapper element. SeeCustom CSS.
---
##### popoverClassName
string | undefined
Custom classes of popover wrapper element. SeeCustom CSS.
---
##### popoverClassNameDisableDefault
boolean | undefined
Disables default classes of popover wrapper element.
There are some default class names with essential styles applied to the popover wrapper element. This setting disables them as an escape hatch for customization. See Custom CSS.
---
##### desktopMediaQuery
string
CSS media query specifing when the widget should behave as displayed on desktop. By default, widget behaves as mobile-first, filling entire device screen with results dropdown.
---
type
### QuickSearchWidgetProps
Quick Search component configuration options
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
QuickSearchCreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-js";
({
// ...ommited code...
: ({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
},
});
```
---
##### initialQuery
string | undefined
String to be prefilled into the search input
---
##### minSearchCharactersCount
number
Minimum length of search query for search request to be sent.
---
##### typingDebounceDuration
number | undefined
Maximum duration between keystrokes in milliseconds before search request is made.
---
##### primaryResultsIndex
number | undefined
Index of request in a batch from which the results are considered to be navigable by arrow keys.
---
##### InputComponent
FC
Component responsible for rendering the widget input.
---
##### TriggerComponent
FC
Component responsible for rendering the widget trigger on mobile devices.
---
##### DropdownComponent
FC
Component responsible for rendering the widget dropdown.
---
##### className
string | undefined
Custom classes of widget wrapper element. SeeCustom CSS.
---
##### popoverClassName
string | undefined
Custom classes of popover wrapper element. SeeCustom CSS.
---
##### popoverClassNameDisableDefault
boolean | undefined
Disables default classes of popover wrapper element.
There are some default class names with essential styles applied to the popover wrapper element. This setting disables them as an escape hatch for customization. See Custom CSS.
---
##### desktopMediaQuery
string
CSS media query specifing when the widget should behave as displayed on desktop. By default, widget behaves as mobile-first, filling entire device screen with results dropdown.
---
class
### QuickSearchWidgetState
Class exposing quick search widget state for use in custom templates
#### Properties
##### isDesktop
boolean
Indicates that the widget is displayed on desktop device.
---
##### reset
() => void
Resets the widget to its initial state
---
##### inputProps
{ value: string; onChange: (event: ChangeEvent) => void; onKeyDown: (event: KeyboardEvent) => void; onClick: () => void; ref: (element: HTMLElement | null) => void; }
Properties to be passed to a input component.
---
##### triggerProps
{ ref: (element: HTMLElement | null) => void; onClick: () => void; }
Properties to be passed to the trigger button of a mobile widget.
---
##### closeButtonProps
{ type: "button"; onClick: () => void; onTouchEnd: () => void; }
Properties to be passed to the close button of a mobile dropdown.
---
##### items
(index: number) => { key: string; id: string; recommId: string; values: { \[key: string\]: any; }; metadata: {} | undefined; itemProps: { tabIndex: number; "data-search-result-id"?: string | undefined; onKeyDown: (event: KeyboardEvent) => void; }; }\[\]
Getter for current results of the request batch. The `index` parameter indicates an index of results in the Batch Request for which to return items.
---
##### isExpanded
boolean
Boolean flag indicating that the widget dropdown is open.
---
##### isLoading
boolean
Boolean flag indicating that a request for new results is in flight.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
---
# Quick Search Widget (React)
> Source: https://docs.recombee.com/widget-sdks/quick-search-widget-react
> For the complete documentation index, see [llms.txt](/llms.txt).
# Quick Search Widget (React)
> A React component widget that enables users to perform real-time product searches with instant results, enhancing product discoverability and conversion.
Use this library when you want to render a widget and you are using React and JSX in your project.
This widget library is version 0.2.23 and the API can change. Please specify exact version when installing.
## Installation
Install `@recombee/quick-search-widget-react@0.2.23` and`recombee-js-api-client` packages using your preferred NPM package manager. This example is using `pnpm`.
```
pnpm add @recombee/quick-search-widget-react@0.2.23 recombee-js-api-client
```
Always remember to apply the default CSS file distributed alongside the widget library, as shown in the examples.
## Client Initialization
The widget loads recommendation data using [Recombee API Client](/js_client). Here is how to initialize the client with necessary configuration for a specific database:
```
import { } from "recombee-js-api-client";
const = "[database-id]";
const = "[database-public-token]";
const = "[database-region]";
export const = new (, , {
: ,
});
```
The Database Public Token can be found in the Admin UI[Database Settings Page](https://admin.recombee.com/go-to-database/settings).
The widget also needs to be provided a `createRequest` function, which instantiates a client request class to define which data to pull from the database. Use Scenario ID which can be found on Admin GUI[Database Scenarios Page](https://admin.recombee.com/go-to-database/scenarios).
Quick Search widget requires the `createRequest` function to return a Batch Request. For a basic case of single search request, always wrap it in a batch.
```
import { type } from "@recombee/quick-search-widget-react";
import { , , } from "recombee-js-api-client";
const : = ({ }) => {
return new (
[
new (userId, , 5, {
: "search-items",
: true,
: true,
}),
new (userId, , 5, {
: "search-categories",
: true,
}),
],
{
: true,
},
);
};
```
### Providing User ID
Each visitor of your website should be identified by a user identificator (`userId`) to correlate user activity and deliver best possible recommendation performance. The `userId` should preferrably originate from your user's account details when the user is authenticated or as some session-persistent random ID when they are anonymous. The SDK provides utility which generates random user id and saves it to a cookie to cover the latter case:
```
import { type } from "@recombee/quick-search-widget-react";
import { , , } from "recombee-js-api-client";
import { } from "@recombee/carousel-widget-react";
let : string | undefined;
if (authenticatedUserId) {
= authenticatedUserId;
} else {
= .();
}
const : = ({ }) => {
return new (
[
new (, , 5, {
: "search-items",
: true,
: true,
}),
new (, , 5, {
: "search-categories",
: true,
}),
],
{
: true,
},
);
};
```
## Basic Example
The widget in this example uses the DefaultItem component to render each recommendation in a consistent layout.
The resulting widget is inserted into the element specified by the`container` field.
Values of the recommended items - such as title, image URL, or link URL - are obtained from the API response and accessed via `props.result?.values`.
Ensure that [returnProperties: true](/api/recommendations#recommend-items-to-user-param-returnProperties) is set in the request, and optionally use[includedProperties](/api/recommendations#recommend-items-to-user-param-includedProperties)to control which item properties are returned.
```
import {
,
,
,
,
,
,
,
} from "@recombee/quick-search-widget-react";
import "@recombee/quick-search-widget-react/dist/styles.css";
export default () => {
return (
< ="flex justify-center p-12">
< ="@container-normal">
<
={}
={}
={3}
="(min-width: 1000px)"
="lg:w-[var(--qs-input-width)] lg:flex lg:justify-center"
={() => (
< ="flex w-[400px] text-[#374040]">
<
={.}
={{ : `Search for "table"...` }}
/>
>
)}
={() => (
<
{.....}
="flex size-[38px] items-center justify-center rounded-sm bg-[#3bc4a1] text-white"
>
< />
>
)}
={() => (
< ="mt-1 flex h-full max-h-full min-h-0 flex-col rounded-sm bg-white text-[#374040] shadow-2xl lg:h-auto lg:max-w-[900px] lg:min-w-[600px]">
{!.. && (
< ="flex items-center gap-2 p-2">
< ="flex-grow">
<
={.}
={{ : `Search for "table"...` }}
/>
>
<
{.....}
="flex size-[38px] items-center justify-center"
>
< />
>
>
)}
< ="flex min-h-0 flex-grow flex-col">
< ="px-4 py-4 pb-2 text-sm font-semibold text-[#3f91ff]">
Results
>
< ="overflow-auto p-2">
{..(0).(() => (
<
={.}
={(
.?.,
.,
)}
={
<
="size-16 overflow-hidden rounded-lg"
={`${.?.}`}
={600}
={400}
/>
}
={.?.}
={.?.}
={`USD ${.?.}`}
{....}
/>
))}
>
>
>
)}
/>
>
>
);
};
```
## Custom Template
You can customize the appearance and behavior of the Quick Search Widget by overriding its individual components:
* [DropdownComponent](#api/QuickSearchWidgetProps.DropdownComponent) – Renders the dropdown containing search results.
* [InputComponent](#api/QuickSearchWidgetProps.InputComponent) – Handles the search input field where users type their queries.
* [TriggerComponent](#api/QuickSearchWidgetProps.TriggerComponent) – Controls how the widget is opened on mobile devices.
The example also demonstrates how to make the search form submittable to a dedicated results page using a `submit` button.
```
import {
,
,
,
,
,
,
} from "@recombee/quick-search-widget-react";
import "@recombee/quick-search-widget-react/dist/styles.css";
export default () => {
return (
< ="flex justify-center p-12">
< ="@container-normal">
<
={}
={}
={3}
={1000}
="(min-width: 1000px)"
={() => (
<
="GET"
="https://example.com/search"
="_blank"
="flex w-[400px] gap-2 text-[#374040]"
>
< ="relative flex flex-grow overflow-hidden rounded-lg border border-[#d9dbdb]">
< ="absolute flex size-[38px] items-center justify-center text-[#737979]">
< />
>
<
="q"
="text"
="block h-[39px] w-full indent-[38px] outline-hidden"
={`Search for "table"...`}
{.....}
/>
{.. && (
< ="rb:absolute rb:top-2.25 rb:right-2.25 rb:h-5 rb:w-5" />
)}
>
<
="submit"
="rounded-lg bg-[#3f91ff] px-5 py-2.5 text-sm font-medium text-white focus:ring-4 focus:ring-blue-300 focus:outline-hidden"
>
Search
>
>
)}
={() => (
<
{.....}
="flex size-[38px] items-center justify-center rounded-sm bg-[#3bc4a1] text-white"
>
< />
>
)}
={() => (
< ="mt-1 flex h-full max-h-full min-h-0 flex-col rounded-sm bg-white text-[#374040] shadow-2xl lg:h-auto lg:max-w-[900px] lg:min-w-[600px]">
{!.. && (
< ="flex items-center gap-2 p-2">
< ="flex-grow">
< ="relative flex flex-grow overflow-hidden rounded-lg border border-[#d9dbdb]">
< ="flex size-[42px] items-center justify-center text-[#737979]">
< />
>
<
="text"
="block w-full outline-hidden"
="Search in docs..."
{.....}
/>
{.. && (
< ="absolute top-2.5 right-2.5 h-5 w-5 animate-spin rounded-full border-2 border-dashed border-current text-[#d9dbdb] [--animate-spin:spin_3s_linear_infinite]" />
)}
>
>
<
{.....}
="flex size-[38px] items-center justify-center"
>
< />
>
>
)}
< ="flex min-h-0 flex-grow flex-col">
< ="px-4 py-4 pb-2 text-sm font-semibold text-[#3f91ff]">
Results
>
< ="overflow-auto p-2">
{..(0).(() => (
<
={.}
={(
.?.,
.,
)}
{....}
="flex items-center gap-4 rounded-sm p-2 outline-hidden hover:bg-[#f7f7f7] focus:bg-[#f7f7f7]"
>
<>
<
="size-16 overflow-hidden rounded-lg"
={`${.?.}`}
={600}
={400}
/>
>
< ="rb:flex-grow">
< ="rb:font-semibold rb:text-nowrap rb:text-ellipsis rb:overflow-hidden">
{.?.}
>
< ="rb:text-[#737979] rb:text-nowrap rb:text-ellipsis rb:overflow-hidden">
{.?.}
>
>
< ="rb:font-bold rb:text-[#3f91ff] rb:text-nowrap rb:text-ellipsis rb:overflow-hidden">{`USD ${.?.}`}>
>
))}
>
>
>
)}
/>
>
>
);
};
```
## Multi-Type Search Results
You can use the Quick Search Widget to display multiple types of results. For example, showing not only items but also categories or brands using the[Search Item Segments](/api/search#search-item-segments) requests.
All search requests are sent together in a single[Batch](/api/miscellaneous#batch) request.
```
import {
,
,
,
,
,
,
,
} from "@recombee/quick-search-widget-react";
import "@recombee/quick-search-widget-react/dist/styles.css";
const : = ({ }) => {
return new (
[
new ("userId", , 5, {
: "search",
: true,
: true,
}),
new ("userId", , 5, {
: "search-brands",
: true,
}),
],
{
: true,
},
);
};
export default () => {
return (
< ="flex justify-center p-12">
< ="@container-normal">
<
={}
={}
={3}
={0}
="(min-width: 1000px)"
="lg:w-[var(--qs-input-width)] lg:flex lg:justify-center"
={() => (
< ="flex w-[400px] text-[#374040]">
<
={.}
={{ : `Search for "table"...` }}
/>
>
)}
={() => (
<
{.....}
="flex size-[38px] items-center justify-center rounded-sm bg-[#3bc4a1] text-white"
>
< />
>
)}
={() => (
< ="mt-1 flex h-full max-h-full min-h-0 flex-col rounded-sm bg-white text-[#374040] shadow-2xl lg:h-auto lg:max-w-[900px] lg:min-w-[600px]">
{!.. && (
< ="flex items-center gap-2 p-2">
< ="flex-grow">
<
={.}
={{ : `Search for "table"...` }}
/>
>
<
{.....}
="flex size-[38px] items-center justify-center"
>
< />
>
>
)}
< ="flex">
< ="flex min-h-0 flex-col">
< ="px-4 py-4 pb-2 text-sm font-semibold text-[#3f91ff]">
Segments
>
< ="overflow-auto p-2">
{..(1).(() => (
<
={.}
={(
.?.,
.,
)}
{....}
="flex items-center gap-2 rounded-sm p-2 text-nowrap outline-hidden hover:bg-[#f7f7f7] focus:bg-[#f7f7f7]"
>
< ="flex-grow">
< ="font-semibold">{.}>
>
>
))}
>
>
< ="flex min-h-0 min-w-0 flex-grow flex-col">
< ="px-4 py-4 pb-2 text-sm font-semibold text-[#3f91ff]">
Results
>
< ="overflow-y-auto p-2">
{..(0).(() => (
<
={.}
={(
.?.,
.,
)}
={
<
="size-16 overflow-hidden rounded-lg"
={`${.?.}`}
={600}
={400}
/>
}
={.?.}
={.?.}
={`USD ${.?.}`}
{....}
/>
))}
>
>
>
>
)}
/>
>
>
);
};
```
## API Reference
const
### QuickSearchWidget
Quick Search widget component
type
### QuickSearchWidgetProps
Quick Search component configuration options
#### Properties
##### apiClient
ApiClient
Instance of Recombee JS API Client. See[Example](#client-initialization).
---
##### createRequest
QuickSearchCreateRequestFunction
Request factory function. See[Quick Example](#client-initialization) or visit[API Reference](/api) for overview of available requests.
---
##### onRecommResponse
WidgetRecommResponseCallback | undefined
Callback function allowing to intercept and inspect recommendation request+response made by widget.
```
import React from "react";
import { } from "@recombee/carousel-widget-react";
<
// ...ommited code...
={({ , }) => {
// use data from request and response for any purpose, i.e. internal tracking
}}
/>;
```
---
##### initialQuery
string | undefined
String to be prefilled into the search input
---
##### minSearchCharactersCount
number
Minimum length of search query for search request to be sent.
---
##### typingDebounceDuration
number | undefined
Maximum duration between keystrokes in milliseconds before search request is made.
---
##### primaryResultsIndex
number | undefined
Index of request in a batch from which the results are considered to be navigable by arrow keys.
---
##### InputComponent
FC
Component responsible for rendering the widget input.
---
##### TriggerComponent
FC
Component responsible for rendering the widget trigger on mobile devices.
---
##### DropdownComponent
FC
Component responsible for rendering the widget dropdown.
---
##### className
string | undefined
Custom classes of widget wrapper element. SeeCustom CSS.
---
##### popoverClassName
string | undefined
Custom classes of popover wrapper element. SeeCustom CSS.
---
##### popoverClassNameDisableDefault
boolean | undefined
Disables default classes of popover wrapper element.
There are some default class names with essential styles applied to the popover wrapper element. This setting disables them as an escape hatch for customization. See Custom CSS.
---
##### desktopMediaQuery
string
CSS media query specifing when the widget should behave as displayed on desktop. By default, widget behaves as mobile-first, filling entire device screen with results dropdown.
---
class
### QuickSearchWidgetState
Class exposing quick search widget state for use in custom templates
#### Properties
##### isDesktop
boolean
Indicates that the widget is displayed on desktop device.
---
##### reset
() => void
Resets the widget to its initial state
---
##### inputProps
{ value: string; onChange: (event: ChangeEvent) => void; onKeyDown: (event: KeyboardEvent) => void; onClick: () => void; ref: (element: HTMLElement | null) => void; }
Properties to be passed to a input component.
---
##### triggerProps
{ ref: (element: HTMLElement | null) => void; onClick: () => void; }
Properties to be passed to the trigger button of a mobile widget.
---
##### closeButtonProps
{ type: "button"; onClick: () => void; onTouchEnd: () => void; }
Properties to be passed to the close button of a mobile dropdown.
---
##### items
(index: number) => { key: string; id: string; recommId: string; values: { \[key: string\]: any; }; metadata: {} | undefined; itemProps: { tabIndex: number; "data-search-result-id"?: string | undefined; onKeyDown: (event: KeyboardEvent) => void; }; }\[\]
Getter for current results of the request batch. The `index` parameter indicates an index of results in the Batch Request for which to return items.
---
##### isExpanded
boolean
Boolean flag indicating that the widget dropdown is open.
---
##### isLoading
boolean
Boolean flag indicating that a request for new results is in flight.
---
const
### ItemImage
Item image component
type
### ItemImageProps
Item Image properties
#### Properties
##### src
string | null | undefined
Image URL
---
##### missingImageSrc
string | undefined
URL of an image to display when the main image could not be loaded.
---
##### className
string | undefined
Image wrapper class name
---
##### imgClassName
string | undefined
Image class name
---
##### width
number | undefined
Image width in pixels
---
##### height
number | undefined
Image height in pixels
---
##### verticalAlignment
"top" | "center" | "bottom" | undefined
Image vertical alignment
---
##### horizontalAlignment
"center" | "left" | "right" | undefined
Image horizontal alignment
---
##### fittingAlgorithm
"cover" | "scale\_down" | undefined
Image fitting algorithm
---
function
### addRecommIdQueryParam
Utility function to append `recombee_recomm_id` parameter to an url string. For usage in widget template to construct item link URL.
---
# No-Code Widgets
> Source: https://docs.recombee.com/no-code-widgets
> For the complete documentation index, see [llms.txt](/llms.txt).
# No-Code Widgets
No-Code Widgets are the easiest way to get recommendations and full-text search into your site.
Setting No-Code Widget in the Admin UI
## No-Code Widget Types
No-Code Widgets can be configured in the Admin UI. They are deployed into a website or app using an embed code.
We provide widgets both for displaying recommended items ([Recommend Items To User](#html-widget-recommending-items-to-user),[Recommend Items To Item](#html-widget-recommending-items-to-item)) and for [full-text search](#html-widget-full-text-search).

Grid No-Code Widget
A box with an adjustable number of items depending on available width (e.g. 5 items horizontally on desktop and 3 items vertically on mobile).

Quick Search No-Code Widget
A widget showing full-text search results based on the user’s query. See the [Full-text Search Widget](#html-widget-full-text-search) section for more details.

Infinite Feed No-Code Widget
A feed of items that incrementally loads more content upon reaching the end of the box.

Carousel No-Code Widget
A box that loads additional recommendations upon clicking the arrow button.
## Displaying Recommendations
Each No-Code Widget is linked to a [Scenario](/scenarios) \- a place on your site where the recommendations are displayed. You can set various settings for each Scenario in the Admin UI. Learn more in the [Scenarios page](/scenarios/settings-in-admin-ui).
**The Scenario also defines the type (endpoint) of the recommendations:**
* **Recommend Items to User** \- The system recommends items to a given user depending on the user's personal taste. This case can be used for example on your homepage.
* **Recommend Items to Item** \- The system recommends items that are related to a given item. The system can also take into account the target user, which can be useful on the page of a product or article, since the endpoint will give the user a list of related items that they might also be interested in.
* **Search Items** \- A personalized full-text search based on the user's query.
To create a new No-Code Widget, go to the [Create No-Code Widget](https://admin.recombee.com/go-to-database/create-recommendation-widget) page in the Admin UI and select the type of the widget that you want to create (e.g. Carousel or Grid).
If you don't have a [Scenario](/scenarios) for the Widget yet, you will be prompted to create one at this point.
You can set which Item Properties will be shown in the Widget and also all kinds of visual settings (e.g. font, colors, borders, and many more). You can also set how many items will be shown on different types of devices.
### Recommending Items to User
In the case of [Recommend Items To User](/api/recommendations#request-recommend-items-to-user) [Scenarios](/scenarios), no additional data needs to be provided to the widget - simply copying the embed code into your website is enough.
You may want to use some of the embed code's [optional parameters](#html-widget-optional-embed-code-params) (such as a dynamic filter),[fine-tune the visual appearance using your own CSS](#html-widget-visual-fine-tuning) or [provide your own user IDs](#html-widget-own-user-tracking).
### Recommending Items to Item
#### Providing the Item ID
In case of the [Recommend Items To Item](/api/recommendations#request-recommend-items-to-item) [Scenarios](/scenarios)(e.g. at product detail, read next, watch next, etc.), the ID of the currently displayed item needs to be provided to the embed code snippet.
[](/img/gui/html_widget_item_id.png)
Item ID placeholder in the Embed Code
Different systems have different ways to acquire the item ID. Here is an example of setting the item ID in a [Shopify](https://www.shopify.com/)theme, using the [product object](https://shopify.dev/docs/themes/liquid/reference/objects/product):
HTML
```
```
#### Sending Interactions
In the case of [Recommend Items To Item](/api/recommendations#request-recommend-items-to-item) [Scenarios](/scenarios), besides showing recommendations to users, the No-Code Widget can also automatically send the information that the user viewed the item (e.g. product, article, etc.) to Recombee.
This simplifies the basic integration of Recombee into your website, as the only step left which is not covered by the No-Code Widget is providing the catalog of your Items. This can be done by setting up a [Catalog Feed](/catalog_feeds) in the [Recombee Admin UI](https://admin.recombee.com) or by [using an SDK](/getting_started#getting-started-catalog).
Sending the interaction can be enabled in the _Embed Code_ section. The interaction which is being sent is a [Detail View](/api/interactions#request-add-detail-view).
[](/img/gui/html_widget_send_interaction.png)
To send the interaction, enable the "Also send Detail View interaction" option
## Quick Search No-Code Widget
The Quick Search No-Code Widget enables you to show items or even [Item Segments](/segmentations) (categories, genres, artists, etc.) based on the user's full-text search query.
[](/img/gui/quick-search-widget.png)
Setting Quick Search No-Code Widget in the Admin UI
### Widget Sections
The Quick Search No-Code Widget can contain multiple sections. Each of these is connected to a [Scenario](/scenarios).
The number of Search requests sent by the Widget is equal to the number of used sections.
In the _Layout_ menu, you can change the order of the displayed sections by moving them (drag and drop), as well as the layout of the sections (e.g. from horizontal to vertical).
[](/img/gui/search-widget-sections.png)
Quick Search No-Code Widget with 3 sections: Segments, Hero, and Items
The following sections are available:
* **Items** \- This section is always present and shows the Items that match your search query. You can present these as a grid or a list.
* **Hero** \- An optional section that highlights the top found Item. This Item is often the most relevant one and takes up the most space in the widget.
* **Segments** \- An optional section that displays matching [Item Segments](/segmentations) (categories, genres, artists, vendors, etc.) by internally using the [Search Item Segments](/api/search#request-search-item-segments) endpoint.
**Items** and **Hero** sections show the following elements of each Item:
* Title,
* Image,
* Description,
* Highlighted Information (often the price of the item).
You can specify which Item Properties will be used within these elements.
In the **Segments** section, only the Segment ID is shown. This can be the name of the category, genre, artist, vendor, etc.
---
All Items and Item Segments shown in the widget are clickable and will redirect the user to a specified URL.
For Items, this URL is constructed from an Item Property that you specify. This property should be the entire URL or contain a unique identifier of the Item (e.g. an Item ID or a URL slug).
For Item Segments, the URL is constructed from the Segment ID.
For all URLs, you can specify a prefix and a suffix. This is useful when you want to construct the URL manually.
**Constructing a URL from an Item Segment ID:**
* Prefix: `https://mypage.com/categories/`
* Suffix: `.html`
* Segment ID: `Office Electronics`
The resulting URL will be `https://mypage.com/categories/office-electronics.html`.
**Constructing a URL from an Item ID:**
* Prefix: `https://mypage.com/products/`
* Suffix: _none_
* Link Property: `item_id`
* Item Property `item_id`: `product-42`
The resulting URL will be `https://mypage.com/products/product-42`.
**Using a URL Item Property:**
* Prefix: _none_
* Suffix: _none_
* Link Property: `url`
* Item Property `url`: `https://mypage.com/products/product-42`
The resulting URL will be `https://mypage.com/products/product-42`.
### Form Behavior
The _Form Behavior_ tab in the No-Code Widget editor (shown as a gear icon) allows you to fine-tune the behavior of the search input.
There you can set the following settings:
* **Start on** \- How many characters the search query should contain before the search requests are fired.
* **Debounce** \- The time in milliseconds that the widget waits before sending another search request.
* **Submit URL** \- Whether there should be a submit button that redirects the user to a dedicated search page, as well as the path of this search page and the name of the _search string_ query parameter.
### Deployment
To deploy the No-Code Widget, simply copy the embed code into the place where the search input should be rendered.
## Using Custom Styles
The No-Code Widget Editor offers a wide range of settings to customize the visual appearance of the widget.
However, you may want to further fine-tune the appearance to match the style of your website.
You can do this by using your own _CSS (Cascading Style Sheets)_ to change the appearance of the widget elements.
### No-Code Widgets
You can add your custom class names in four places in the No-Code Widget Editor using the `{}` icon:
* The _Grid Box_ around the whole widget,
* The _Item Box_ around a single recommended item,
* _Image_ of a recommended item - both the `img` element and the wrapper around it,
* Individual _Properties_ of a recommended item.
[](/img/gui/html_widget_class_names.png)
Setting the `price-row` class name to the row with the _price_
#### Class Name Templates
When applying the class names to elements that belong to a particular recommended item (_Image_ and _Properties_ sections), you can use the property values of the particular item to construct the class names using the `${context.entity.propertyName}` syntax.
Assume the following item:
| Item ID | isOnSale Boolean | reviewRating Integer |
| ------- | ---------------- | -------------------- |
| item-42 | true | 5 |
The following class names can be created:
* `on-sale-${context.entity.isOnSale}` sets the class `on-sale-true` on the element
* `rating rating-${context.entity.reviewRating}` sets the classes `rating rating-5` on the element
### Quick Search No-Code Widget
Search Widget DOM elements have static class names in the form of `recombee-quick-search-widget-*`, which do not change. You can use these classes to provide custom CSS.
Please do not use class names in the form of `rcmbws-*`, as these are generated and can change in future releases.
## Optional Embed Code Parameters
You may want to filter the recommendations, boost items, or set the logic of the recommendations.
If possible, we recommend setting these parameters in the Scenario in the Admin UI.
However, you may also want to set them dynamically. This can be done by adding optional parameters to the `InitializeRecommendationWidget` call:
### Filter
Use the `filter` parameter to apply a custom [ReQL](/reql) filter. For example, you can restrict displayed items to a specific category:
HTML
```
```
### Booster
Use the `booster` parameter to apply a custom [ReQL](/reql) booster. For example, you can boost items that are near the current position of the user:
HTML
```
```
### Logic
Use the `logic` parameter to set the [Logic](/logics) for the used recommendation requests, including their settings. For example, you can set the Logic to recommend popular items in the country of the user:
HTML
```
```
### Widget Positioning
By default, the position of the widget on your page is determined by the position of the _div_ element generated for you in the embed code snippet.
However, in some cases, you may want to set the position of the widget programmatically, such as when deploying the widget using a tag manager (such as [Google Tag Manager](#html-integration-gtm)).
You can specify where the widget will be rendered by giving its relative position to another element.
Use one of these optional parameters to specify this element:
* `insertBeforeElementSelector`: The widget will be inserted before the first element matching this selector (id, class, etc.).
* `insertAfterElementSelector`: The widget will be inserted after the first element matching this selector.
* `prependToElementSelector`: The widget will be inserted as the first child of the first element matching this selector.
* `appendToElementSelector`: The widget will be inserted as the last child of the first element matching this selector.
HTML
```
```
### Hiding an Empty Widget
In some cases, such as your database being empty or the widget scenario produces no results due to e.g. applied filters, the widget may fetch zero items. You may want to hide the widget itself and/or some other elements in your page such as a heading preceding the widget content.
* `hideOnEmptyRecommendations`: The widget is hidden when no items are available.
* `hideOnEmptyRecommendationsElementsSelectors`: Selected elements in page are hidden when no items are available.
HTML
```
```
### Using Widget Data Programmatically
You can supply a callback function that receives data about each recommendation request made by the widget:
HTML
```
```
* Callback parameters:
* `recombeeRequest`: Recombee API client request, either a single request or a [Batch](/api/miscellaneous#batch).
* `recombeeResponse`: Resulting recommendations data, either a single response or a Batch response.
* `url`: [Recombee API URL](/regions) to which the request was sent.
* `request`: Standard `fetch` `RequestInit` object.
* `response`: Standard `fetch` `Response` object.
## Usage with Google Tag Manager
To deploy a widget using GTM, create a _Custom HTML Tag_ and copy-paste the widget embed code to the Tag HTML content.
Set a _Page View_ trigger for pages where the widget should be deployed and use [positioning parameters](#html-integration-positioning-of-the-widget) to insert the widget to a specific place on your page.
## Cookies Information
To provide the most relevant recommendations, Recombee by default identifies the user using first-party cookies on the user's browser.
The cookie is set by Recombee Integration script, which is used to track interactions or render recommended items in No-Code Widget. The cookie doesn't identify your users personally.
Important
You may need to notify your users about the use of tracking cookies depending on your user's country privacy laws. This is usually done by using a cookie manager deployed to your website. Please consult your legal team to determine whether this step is necessary.
As we use first-party cookies, Recombee tracks your users only on your website - Recombee does no cross-site tracking. Read more about the difference between first-party and third-party cookies [here](https://clearcode.cc/blog/difference-between-first-party-third-party-cookies/).
### Cookies Set by the Recombee Widget Integration
| Name | Description | Duration | Data Type |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | --------- |
| _\_rcmbid_ | \_rcmbid is set each time a user lands on a page with the Recombee Integration script. The cookie is used to preserve the unique Recombee User ID. This ensures that all interactions performed by the unique visitor are attributed to a common anonymous ID. | 365 days, refreshed on each visit | String |
### Users with Disabled Cookies
Recombee doesn't track or record users who have cookies disabled.
### Custom User Tracking
If you already track the users on your site, you can provide the ID of the user to the Recombee Integration script. You can select this option in the _Embed Code_ section when creating the No-Code Widget.
In this case, no cookie is set by the widget.
#### Example
Here is an example of using the Recombee with Google Analytics user IDs:
HTML
```
```
---
# Catalog Feeds
> Source: https://docs.recombee.com/catalog_feeds
> For the complete documentation index, see [llms.txt](/llms.txt).
# Catalog Feeds
Setting a catalog feed in the [Recombee Admin UI](https://admin.recombee.com) is an alternative to[uploading the items catalog using our API](/getting_started#getting-started-catalog).
We periodically download your feed and update items accordingly. The default update period is 4 hours - if it does not match your specific needs, please contact [support@recombee.com](mailto:support@recombee.com).
* Supported protocols for fetching: `http`, `https`, `ftp` and `sftp`.
* Supported feeds compressions: `.zip` and `.gz`.
We support the following types of feed formats:
* [Google Merchant XML / TSV](/catalog_feeds/google-merchant-feed)
* [Atom / RSS](/catalog_feeds/atom-rss-feed)
* [Custom XML](/catalog_feeds/custom-xml-feed)
* [Custom JSON](/catalog_feeds/custom-json-feed)
* [Custom CSV](/catalog_feeds/custom-csv-feed)
* [Heureka XML](/catalog_feeds/heureka-xml-feed)
## Step-by-Step Video Tutorial
## General Notes
* The property name _itemId_ is reserved.
* Items deleted from feeds are not deleted in Recombee catalog. Instead, they can be updated as _not available_. For more details see [Handling of removed items](#feeds-availability-property).
### IDs with Special Characters
The IDs of the items in Recombee may consist of digits, latin letters, underscores, colons, minus signs, at sign, and dot.
If the IDs in your feed do not follow this format (the ID is for example the URL of the item), enable the _MD5 Item IDs_ option in the_Settings_. An [MD5 hash](https://en.wikipedia.org/wiki/MD5) of the original ID value is then used as the ID.
You then need to use the MD5 hash also when you send interactions to Recombee and when you request[Items to Item recommendation](/api/recommendations#request-recommend-items-to-item).
In JavaScript the MD5 hash of the original ID can be obtained for example like this:
HTML
```
```
### Handling of Removed Items
The Feeds processor can automatically set items that have been removed from the feed as unavailable.
To use this feature, pick the item property that determines availability, and provide the value which denotes the unavailable items:
[](/img/feeds/feeds_availability_property.png)
You can then use this item property in your [Filters](/scenarios/settings-in-admin-ui#filters).
---
# Google Merchant Feed
> Source: https://docs.recombee.com/catalog_feeds/google-merchant-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Google Merchant Feed
## Format
* Specification:
* We support both `.xml` and `.tsv` (tab separated text file) variants. Both `.zip` and `.gz` compression is supported.
* In addition, we support `.csv` (comma separated) variant (not officially supported by Google)
## Tips & Tricks
* You can use item property `availability` for[filtering out](/reql_filtering_and_boosting) from the recommendations the items that are not available anymore.
The filter that should be passed to[recommendation requests](/api/recommendations) is:
ReQL
```
'availability' == "in stock"
```
Only items in stock will be recommended. You can achieve this also by setting the predefined Filter [Business Rule](/scenarios/settings-in-admin-ui#filters) _Items in stock \[Google Merchant\]_ to your [Scenario](/scenarios).
* Ids of items are case sensitive - please check that you are using the same case as is used in the feed when you[send interactions](/getting_started#getting-started-interactions).
* You can use for example following JavaScript snippet to get recommended items along with their title, description, link, image link and price:
JS
```
client.send(new recombee.RecommendItemsToItem(itemId, userId, 3,
{
returnProperties: true,
includedProperties: ['title', 'description', 'link', 'image_link', 'price'],
filter: "'availability' == \"in stock\"",
scenario: 'related_items'
}),
(err, resp) => {
if(err) {
console.log("Could not load recomms: ", err);
return;
}
console.log(resp);
// Show recommendations
});
```
For more info see the [JavaScript library](https://github.com/recombee/js-api-client).
---
# Atom / RSS Feed
> Source: https://docs.recombee.com/catalog_feeds/atom-rss-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Atom / RSS Feed
Atom / RSS feeds are used by the news websites and also many blog pages or podcasts to provide structured information about the offered content.
## How to Set Up
1. Set the URL of your Atom / RSS feed.
2. The feed gets processed and a list of properties that were recognized in the feed is presented in the Suggested properties section. You can pick from this list the properties that you want to synchronize to Recombee.
You can also create a custom new property and set an [XPath](https://www.w3schools.com/xml/xpath_syntax.asp) for it (relative to the item entry). This is needed especially in the case of large _.zip_ feeds which cannot be fully processed in this step to obtain the suggested properties.
3. Continue to _Preview_ and check that you are getting expected data for all the properties. When you are satisfied, confirm the settings and the feed will get scheduled for processing.
[](/img/feeds/setting_feed.gif)
If the IDs in your feed are URLs or contain other special characters, see[IDs with Special Characters](/catalog_feeds#feeds-md5-item-id).
---
# Custom XML Feed
> Source: https://docs.recombee.com/catalog_feeds/custom-xml-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Custom XML Feed
An XML that contains structured information about the items.
## How to Set Up
1. Set the URL of your XML feed.
2. Set _Items Path_ \- the [XPath](https://www.w3schools.com/xml/xpath_syntax.asp) to the root element of the items records
3. Set _Item ID Path_ \- Path (relative to the items path) to the element that contains the itemId. If your IDs contain some special characters, enable the _MD5 Item IDs_ option (see [this section](/catalog_feeds#feeds-md5-item-id) for more details).
4. The feed gets processed and a list of properties that were recognized in the feed is presented in the Suggested properties section. You can pick from this list the properties that you want to synchronize to Recombee.
You can also create a custom new property and set an [XPath](https://www.w3schools.com/xml/xpath_syntax.asp) for it (relative to the item entry). This is needed especially in the case of large _.zip_ feeds which cannot be fully processed in this step to obtain the suggested properties.
5. Continue to _Preview_ and check that you are getting expected data for all the properties. When you are satisfied, confirm the settings and the feed will get scheduled for processing.
For information about handling items deletion and updating items availability see [Handling of removed items](/catalog_feeds#feeds-availability-property).
## Tips & Tricks
* Arrays in XML: if we have set item property `categories` and we want to fill its data, we need to define multiple fields with the same ID inside item entry. It's relative path is `/categories`. It will correctly process and assign 3 values to the property.
```
DramaHorrorThriller
```
---
# Custom JSON Feed
> Source: https://docs.recombee.com/catalog_feeds/custom-json-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Custom JSON Feed
A JSON that contains structured information about the items.
## How to Set Up
1. Set the URL of your JSON feed.
2. Set _Items Path_ \- a path defined by keys of JSON objects to the array with items records
3. Set _Item ID Path_ \- a path (relative to the item entry) to the element that contains the itemId. If your IDs contain some special characters, enable the _MD5 Item IDs_ option (see[this section](/catalog_feeds#feeds-md5-item-id) for more details).
4. The feed gets processed and a list of properties that were recognized in the feed is presented in the Suggested properties section. You can pick from the list properties that you want to synchronize to Recombee.
You can also create a new property and set a path of keys for it (relative to the item entry). This is needed especially in the case of large _.zip_ feeds which cannot be fully processed in this step to obtain the suggested properties.
5. Continue to _Preview_ and check that you are getting expected data for all the properties. When you are satisfied, confirm the settings and the feed will get scheduled for processing.
For information about handling items deletion and updating items availability see[Handling of removed items](/catalog_feeds#feeds-availability-property).
---
# Custom CSV Feed
> Source: https://docs.recombee.com/catalog_feeds/custom-csv-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Custom CSV Feed
A CSV file where each line contains data for a single item.
It is expected that:
* The IDs of the items are contained in the first column
* The first row of the CSV file is a header (contains names of the columns)
The file is automatically analyzed to determine the used delimiter and quoting.
## How to Set Up
1. Set the URL of your CSV feed.
2. The feed gets processed and a list of properties (columns) that were recognized in the feed is presented in the Suggested properties section. You can pick from this list the properties that you want to synchronize to Recombee. You need to set the correct data type for each of the properties.
You can also create a custom new property and set the column name for it. This is needed especially in the case of large _.zip_ feeds which cannot be fully processed in this step to obtain the suggested properties.
3. Continue to _Preview_ and check that you are getting expected data for all the properties. When you are satisfied, confirm the settings and the feed will get scheduled for processing.
For information about handling items deletion and updating items availability see [Handling of removed items](/catalog_feeds#feeds-availability-property).
---
# Heureka XML Feed
> Source: https://docs.recombee.com/catalog_feeds/heureka-xml-feed
> For the complete documentation index, see [llms.txt](/llms.txt).
# Heureka XML Feed
## Format
* Specification:
## Tips & Tricks
* You can use item property `AVAILABLE` for[filtering out](/reql_filtering_and_boosting) from the recommendations the items that are not available anymore.
The filter that should be passed to[recommendation requests](/api/recommendations) is:
ReQL
```
'AVAILABLE'
```
---
# Third-Party Integrations
> Source: https://docs.recombee.com/third-party-integrations
> For the complete documentation index, see [llms.txt](/llms.txt).
# Third-Party Integrations
Recombee offers multiple integrations with third-party services, which make it easier to add recommendations to your website or app.
[Segment Integration: Use the Recombee Destination within the Segment CDP to send interactions in a unified way.](/segment)[Keboola Integration: Use a connector to upload the catalog and interactions, or to get recommendations.](/keboola)[Shoptet GTM Integration: Send interactions from your Shoptet store to Recombee via Google Tag Manager.](/shoptet_gtm_integration)
---
# Segment Integration
> Source: https://docs.recombee.com/segment
> For the complete documentation index, see [llms.txt](/llms.txt).
# Segment Integration
[Segment](https://segment.com) is a Customer Data Platform (CDP).
Segment simplifies collecting and using data from the users of your digital properties (websites, apps, etc). Using it, you can collect, transform, send, and archive your first-party customer data.
The Recombee destination in Segment can send your interaction data (views, purchases, plays, etc.) to Recombee.
Note
This page describes the new version of the Recombee Destination in Segment, called just **Recombee**. For documentation of the old version, called _Recombee AI_, visit the [Segment Documentation](https://segment.com/docs/connections/destinations/catalog/recombee-ai/).
## Getting Started
1. In the Segment web app, navigate to **Connections > Destinations** and click **Add Destination**.
2. Find and select [Recombee](https://app.segment.com/goto-my-workspace/destinations/catalog/actions-recombee) and click **Add Destination**.
[](/img/segment/segment_ui.png)
3. Select a Source to connect to the **Recombee** destination.
4. Navigate to the [Recombee Admin UI](https://admin.recombee.com) and complete the following actions:
* Choose the Recombee Database where you want to send the interactions.
* Click **Settings** in the menu on the left.
* In the **API ID & Tokens** settings section, find the **Database ID** and the **Private Token** of the Database.
5. Back in the Segment app, navigate to the settings page of the Recombee destination you created.
* Copy the **Database ID** from the Recombee Admin UI and paste it into the **Database ID** field in the destination settings.
* Copy the **Private Token** from the Recombee Admin UI and paste it into the **Private Token** field in the destination settings.
[](/img/segment/segment_settings.png)
Once you send the data from Segment to the Recombee destination, you can:
* Open the KPI console of the [Recombee Admin UI](https://admin.recombee.com) to see the numbers of the ingested interactions (updated in realtime).
* Select the ID of an Item (or User) in the Items (or Users) catalog section in the Admin UI to view a specific ingested interaction.
## Settings
Database ID
Required: **Yes**
The ID of the Recombee Database into which the interactions will be sent.
---
Private Token
Required: **Yes**
The private token for the Recombee Database used.
---
Database Region
Required: **Yes**
The Recombee cluster where your Database is located. [Learn more](/regions)
---
API URI
Required: **No**
URI of the Recombee API that should be used. _Keep this field empty unless you are calling the Recombee cluster based in a specific region or you were assigned a custom URI by the Recombee Support team._
---
## Supported Mappings
### Page
If you're new to the Segment Spec, check out the [Page method documentation](https://segment.com/docs/connections/spec/page/) to understand how it works. Here's an example of a Page method call:
JavaScript
```
analytics.page();
```
Segment sends Page calls to Recombee as a [Detail View](/api/interactions#request-add-detail-view).
### Track
If you aren't familiar with the Segment Spec, take a look at the [Track method documentation](https://segment.com/docs/connections/spec/track/)to learn about what it does. Here's an example:
JavaScript
```
analytics.track('Video Content Playing', {
session_id: '12345',
asset_id: '0129370',
position: 20,
total_length: 360,
recomm_id: 'ce52ada4-e4d9-4885-943c-407db2dee837',
});
```
The Recombee Destination can process several [Semantic Events](https://segment.com/docs/connections/spec/semantic/).
**Supported [Ecommerce](https://segment.com/docs/connections/spec/ecommerce/v2/) events:**
| Segment Event | Sent Interaction |
| ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| [Product Viewed](https://segment.com/docs/connections/spec/ecommerce/v2/#product-viewed) | [Detail View](/api/interactions#request-add-detail-view) |
| [Product Added](https://segment.com/docs/connections/spec/ecommerce/v2/#product-added) | [Cart Addition](/api/interactions#request-add-cart-addition) |
| [Product Removed](https://segment.com/docs/connections/spec/ecommerce/v2/#product-removed) | [Delete Cart Addition](/api/interactions#request-delete-cart-addition) |
| [Order Completed](https://segment.com/docs/connections/spec/ecommerce/v2/#order-completed) | [Purchase](/api/interactions#request-add-purchase) for each of the ordered products |
| [Product Added to Wishlist](https://segment.com/docs/connections/spec/ecommerce/v2/#product-added-to-wishlist) | [Bookmark](/api/interactions#request-add-bookmark) |
| [Product Removed from Wishlist](https://segment.com/docs/connections/spec/ecommerce/v2/#product-removed-from-wishlist) | [Delete Bookmark](/api/interactions#request-delete-bookmark) |
| [Product Shared](https://segment.com/docs/connections/spec/ecommerce/v2/#product-shared) | [Bookmark](/api/interactions#request-add-bookmark) |
**Supported [Video](https://segment.com/docs/connections/spec/video/) events:**
| Segment Event | Sent Interaction |
| ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| [Video Playback Started](https://segment.com/docs/connections/spec/video/#video-playback-started) | [View Portion](/api/interactions#request-set-view-portion) with portion = 0 |
| [Video Content Playing](https://segment.com/docs/connections/spec/video/#video-content-playing) | [View Portion](/api/interactions#request-set-view-portion) with portion = position / total\_length |
| [Video Playback Paused](https://segment.com/docs/connections/spec/video/#video-playback-paused) | [View Portion](/api/interactions#request-set-view-portion) with portion = position / total\_length |
| [Video Playback Completed](https://segment.com/docs/connections/spec/video/#video-playback-completed) | [View Portion](/api/interactions#request-set-view-portion) with portion = 1 |
If you want to send interactions from other types of events, you can create your own custom mappings in the Segment web app. [Learn more below](#custom-mappings)
### Screen
For more details on the Screen method, refer to the [Screen method documentation](https://segment.com/docs/connections/spec/screen/). Here's an example call:
Objective-C
```
[[SEGAnalytics sharedAnalytics] screen:@"Home"];
```
Segment converts Screen calls to [Detail View](/api/interactions#request-add-detail-view) interactions.
### Alias
For information about Alias, visit the [Alias method documentation](https://segment.com/docs/connections/spec/alias/). Here's an example of an Alias call:
JavaScript
```
analytics.alias('507f191e81');
```
These Alias calls are mapped to [Merge Users](/api/users#request-merge-users) calls.
### Delete User
Segment sends a [Delete User](/api/users#request-delete-user) call to Recombee on deleting a user. All the associated data associated with the user (including interactions) are removed from Recombee.
### Custom Mappings
The new Action Destinations framework in Segment, which this integration uses, allows you to create custom mappings for your events directly in the Segment web app.
To create a custom mapping, open the destination in the Segment web app, navigate to the **Mappings** tab, and click **New Mapping**.
You can add a predefined mapping, but more importantly, right below the predefined mappings, there is a list of all available actions that you can use to create your own custom mappings.
[](/img/segment/segment_mapping_actions.png)
After selecting an action, you can continue below the list and configure the mapping.
There you can define the event trigger, the fields of the event, and how they correspond to the fields of the interaction.
[](/img/segment/segment_mapping_trigger.png)
## Reporting Successful Recommendations
You should inform Recombee that a specific interaction resulted from a successful recommendation (meaning the recommendations were presented to a user, and the user clicked on one of the items) by setting the ID of the successful recommendation request in the `Recommendation ID` field of the action (this is the `recomm_id` property by default). You can read more about this setting in [Reported Metrics](/admin_ui#reported-metrics).
Sending the `Recommendation ID` gives you precise numbers about successful recommendations in the KPI section of the [Recombee Admin UI](https://admin.recombee.com). This explicit feedback also helps improve the output of the recommendation models.
---
# Keboola Integration
> Source: https://docs.recombee.com/keboola
> For the complete documentation index, see [llms.txt](/llms.txt).
# Keboola Integration
Keboola is a data platform that helps organizations build scalable, automated data pipelines by orchestrating data collection, transformation, and delivery.
Recombee provides two components in Keboola:
* [**Data Destination**](#data-destination) for uploading items, users, and interactions
* [**Data Source**](#data-source) for requesting recommendations
## Data Destination
The Recombee Data Destination for [Keboola](https://keboola.com) uploads items, users, and interactions from CSV tables in Keboola to Recombee to power personalized recommendations and search.
It supports all major Recombee APIs for catalog and behavior data ingestion.
### ✨ Features
* Uploads **Items Catalog** and **Users Catalog**
* Supports all standard **Recombee interactions**:
* `AddDetailView`
* `AddPurchase`
* `AddRating`
* `AddBookmark`
* `AddCartAddition`
* `SetViewPortion`
* Supports **optional fields** (e.g., `timestamp`, `recomm_id`, `additional_data`)
* Gracefully handles bad data (e.g. `NaN`, invalid types) and logs summarizations
### ⚙️ Configuration
You can configure the component directly in the Keboola UI when setting up the component.
| Field | Description |
| ------------- | ------------------------------------------------------------------ |
| Database ID | Your Recombee Database ID |
| Private Token | Associated private token |
| Region | Recombee cluster region of your DB (eu-west, us-west, ap-se, etc.) |
| Batch Size | \[Optional\] Number of requests sent per batch. Defaults to 1000. |
[](/img/keboola/keboola_data_destination_configuration.png)
### 🧱 Input Structure
Place CSV files in `in/tables/`.
#### Catalog
| Filename | Recombee API | Required Columns | Optional Columns |
| --------- | ------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------- |
| items.csv | [SetItemValues](/api/item-properties#request-set-item-values) | item\_id | All others based on your Recombee item properties (e.g. title, price, tags) |
| users.csv | [SetUserValues](/api/user-properties#request-set-user-values) | user\_id | All others based on your Recombee user properties (e.g. subscribed\_topics, age, country) |
#### Interactions
| Filename | Recombee API | Required Columns | Optional Columns |
| ------------------- | -------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------- |
| bookmarks.csv | [AddBookmark](/api/interactions#request-add-bookmark) | user\_id, item\_id | timestamp, recomm\_id, additional\_data |
| cart\_additions.csv | [AddCartAddition](/api/interactions#request-add-cart-addition) | user\_id, item\_id | timestamp, recomm\_id, amount, additional\_data |
| detail\_views.csv | [AddDetailView](/api/interactions#request-add-detail-view) | user\_id, item\_id | timestamp, recomm\_id, duration, additional\_data |
| purchases.csv | [AddPurchase](/api/interactions#request-add-purchase) | user\_id, item\_id | timestamp, recomm\_id, amount, price, profit, additional\_data |
| ratings.csv | [AddRating](/api/interactions#request-add-rating) | user\_id, item\_id, rating | timestamp, recomm\_id, additional\_data |
| view\_portions.csv | [SetViewPortion](/api/interactions#request-set-view-portion) | user\_id, item\_id, portion | timestamp, recomm\_id, additional\_data |
#### Notes
* `item_id` / `user_id` must always be in the **first column** for catalog files.
* Columns such as `tags`, `additional_data`, `imageList` should be passed as valid JSON strings.
### 📤 Example Input - detail\_views.csv
```
user_id,item_id,timestamp,recomm_id,additional_data
user-1,item-10,2025-07-06T21:12:43Z,644c005f-aa99-4bce-aa55-a0c610e80df0,"{""source"": ""newsletter""}"
user-2,item-09,2025-07-06T21:09:13Z,,"{""source"": ""newsletter""}"
user-3,item-05,2025-07-06T21:14:45Z,2d2eb48f-cd65-421a-943c-0e015055fd8e,"{""source"": ""homepage""}"
```
### 📤 Example Input - items.csv
Item properties must be created in the [Recombee Admin UI](https://admin.recombee.com).
```
item_id,title,price,available,date_added,tags
item-01,Wireless Mouse,25.99,true,2025-07-20T10:11:49.039302,"[""electronics"", ""accessory"", ""mouse""]"
item-42,Mechanical Keyboard,75.49,false,2025-08-04T10:11:49.039318,"[""electronics"", ""keyboard""]"
item-77,USB-C Hub,34.9,true,2025-08-19T10:11:49.039321,"[""electronics"", ""usb"", ""hub""]"
```
## Data Source
The Recombee Data Source fetches recommendations from [Recombee](https://www.recombee.com/) via selected recommendation endpoint and exports the results as structured CSV tables.
### ✨ Features
* Supports following **Recombee recommendation endpoints**:
* [Recommend Items to User](https://docs.recombee.com/api/recommendations#recommend-items-to-user)
* [Recommend Items to Item](https://docs.recombee.com/api/recommendations#recommend-items-to-item)
* [Recommend Item Segments to User](https://docs.recombee.com/api/recommendations#recommend-item-segments-to-user)
* Uses batch requests with automatic retry handling
* Supports using [Scenarios](/scenarios)
* Supports [returning item properties](https://docs.recombee.com/api/recommendations#recommend-items-to-user-param-includedProperties) (metadata) of the recommended items
* Outputs results with full Recombee API response for auditability
[](/img/keboola/keboola_data_source.png)
### ⚙️ Configuration
You can configure the component directly in the Keboola UI when setting up the component.
| Field | Description |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Database ID | The ID of your Recombee database (e.g., "your-database-id"). |
| Private Token | The private token used to authenticate requests to Recombee. |
| Region | Region where your Recombee database is hosted (ap-se, ca-east, eu-west, us-west). Defaults to eu-west. |
| Scenario | The recommendation scenario to be used (e.g., "emailing", "related-items"). Should match the scenario set up in Recombee Admin UI. |
| Recommendation Endpoint | Which Recombee endpoint to use for fetching recommendations. Must align with the selected scenario (e.g., Recommend Items to User, Recommend Items to Item, etc.). |
| Number of Recommendations | How many recommended items to fetch per user or item. Integer from 1 to 30\. Defaults to 5. |
| Included Properties | Optional. List of item properties to include in the response (e.g., \["title", "url", "image"\]). |
| Batch Size | Number of users or items to fetch recommendations for in one batch. Optional. Defaults to 100\. Range: 10–10000. |
[](/img/keboola/keboola_data_source_configuration.png)
### 🧱 Input Structure
Place one CSV file into `in/tables/`, depending on the selected recommendation endpoint.
| Filename | Used For Endpoint(s) |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| users.csv | [Recommend Items to User](https://docs.recombee.com/api/recommendations#recommend-items-to-user) / [Recommend Item Segments to User](https://docs.recombee.com/api/recommendations#recommend-item-segments-to-user) |
| items.csv | [Recommend Items to Item](https://docs.recombee.com/api/recommendations#recommend-items-to-item) |
The CSV file must contain a single column with IDs of users / items for which recommendations should be generated.
### Example Input
```
user_id
user_3fa8c1
user_4b92d8
user_7c13f0
user_1d8a9e
```
### 📤 Output Format
The recommendations are exported to `out/tables/recomms.csv`.
| Column | Description |
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| user\_id / item\_id | The ID the recommendation was generated for |
| recomm\_id | Recombee [recommId](https://docs.recombee.com/getting_started#reporting-successful-recommendations) used for tracking |
| recommended\_items / recommended\_item\_segments | List of recommended item or segment IDs |
| api\_response | Full JSON response from Recombee (including e.g., the returned properties) |
#### Example Output - recomms.csv
```
user_id,recomm_id,recommended_items,api_response
user_3fa8c1,cc08bcf0-9d8e-4726-8b21-e47f770316e1,"[""item-165"", ""item-69"", ""item-857""]","{""recommId"": ""cc08bcf0-9d8e-4726-8b21-e47f770316e1"", ""recomms"": [{""id"": ""item-165""}, {""id"": ""item-69""}, {""id"": ""item-857""}], ""numberNextRecommsCalls"": 0}"
user_4b92d8,9c291302-abcd-4ab4-b926-aceac05ad15a,"[""item-165"", ""item-69"", ""item-857""]","{""recommId"": ""9c291302-abcd-4ab4-b926-aceac05ad15a"", ""recomms"": [{""id"": ""item-165""}, {""id"": ""item-69""}, {""id"": ""item-857""}], ""numberNextRecommsCalls"": 0}"
```
#### Notes
* Use the `Included Properties` configuration parameter to include item metadata such as `title`, `url`, `category`, or `price` in the `api_response` column.
* All values in `recommended_items` or `recommended_item_segments` are exported as JSON arrays.
---
# Shoptet GTM Integration
> Source: https://docs.recombee.com/shoptet_gtm_integration
> For the complete documentation index, see [llms.txt](/llms.txt).
# Shoptet GTM Integration
In order to set up GTM integration, you will need to create a [Google Tag Manager](https://tagmanager.google.com/) account.
Recombee GTM integration supports four types of user interactions in the Shoptet platform:
* Add to cart
* Detail view
* Purchase
* Rating
## Shoptet Setup
Follow instructions for initial setup.
## Creating Triggers
Triggers are needed in order to add support for sending Add to cart and Purchase interactions.
Select Triggers in the menu and add a new trigger on the **DOM Ready event** and also **Custom Events** called _“AddToCart”_ and_“Purchase”_.
### DOM Ready Event
1. Navigate to the **Triggers** section
2. Click the **New** button and choose the **DOM Ready** type
3. On the triggers fire selection keep the **All DOM Ready Events** and name the trigger accordingly
[](/img/shoptet_gtm/shoptet-gtm-dom-ready-event.png)
[](/img/shoptet_gtm/shoptet-gtm-dom-ready-event-2.png)
### AddToCart Event
1. Navigate to the **Triggers** section
2. Click the **New** button and choose the **Custom Event** type
3. Fill the **Event name** with _“addToCart”_ and select the **All Custom Events** option below.
[](/img/shoptet_gtm/shoptet-gtm-addtocart.png)
[](/img/shoptet_gtm/shoptet-gtm-addtocart-2.png)
## Creating Tags
Our custom GTM tags will send interactions to Recombee. You can create tags for all supported interactions or just those you want to send.
### GTM Gallery Integration
We have published [Recombee Shoptet integration](https://tagmanager.google.com/gallery/#/owners/recombee/templates/shoptet-gtm-integration), which you can use for easy setup.
Go to the **Tags section**, click **New** and search for the **Recombee Shoptet interactions** template.
### Manual Template Import
While we are waiting for Google approval to be included in the GTM template gallery, you can simply import the Recombee Shoptet template for use.
Download the template file from our Github repository ([GTM Integration Github](https://github.com/recombee/shoptet-gtm-integration) \- _template.tpl_)
1. In GTM select **Templates** in the left side menu and click on**New**
2. Import the template by clicking on the dots and select **Import**
3. Select downloaded _template.tpl_ file and save your new template
Now you can use our template when creating your tags.
### Initialization Tag
We provide one tag with multiple types. You always need to create an initialization tag.
Tag that initializes the environment for sending interactions. You will need it for sending interactions to work.
1. Select **Initialization** type in **Tag Interaction Type**
2. Fill the **Database ID** with the ID of your Recombee database_(e.g., \`shoptet-gtm-example-prod\`)_
3. Fill **region** of your database _(e.g., eu-west)_
4. Fill **public key**
**You can find all the information in the settings of your database in the Recombee admin.**
[](/img/shoptet_gtm/shoptet-gtm-Initialization-tag.png)
### Interaction Tags
You can choose which interactions to send by creating a tag for each type.
#### Detail View
To create a tag for Detail view interaction, select a **Detail View**option in **Tag Interaction Use Case** and name it accordingly.
Click on **Advanced Settings** and **Tag Sequencing**, choose **Fire tag before xxx fires**, and select your **initialization tag** created before.
For **triggering**, select the **DOM Ready** trigger created in the first steps.
[](/img/shoptet_gtm/shoptet-gtm-interaction-tag-detail-view.png)
#### Rating
To create a tag for Rating interaction, select a **Rating** option in**Tag Interaction Use Case** and name it accordingly.
Click on **Advanced Settings** and **Tag Sequencing**, choose **Fire tag before xxx fires**, and select your **initialization tag** created before.
For **triggering**, select the **DOM Ready** trigger created in the first steps.
[](/img/shoptet_gtm/shoptet-gtm-interaction-tag-rating.png)
#### Purchase
To create a tag for Purchase interaction, select a **Purchase** option in **Tag Interaction Use Case** and name it accordingly.
Click on **Advanced Settings** and **Tag Sequencing**, choose **Fire tag before xxx fires**, and select your **initialization tag** created before.
For **triggering**, select the **DOM Ready** trigger created in the first steps.
[](/img/shoptet_gtm/shoptet-gtm-interaction-tag-purchase.png)
#### Cart Addition
To create a tag for Cart addition interaction, select a **Cart addition**option in **Tag Interaction Use Case** and name it accordingly.
Click on **Advanced Settings** and **Tag Sequencing**, choose **Fire tag before xxx fires**, and select your **initialization tag** created before.
For **triggering**, select the **AddToCart** trigger created in the first steps.
[](/img/shoptet_gtm/shoptet-gtm-interaction-cart-addition.png)
## Done!
---
# Integration Tips
> Source: https://docs.recombee.com/integration_tips
> For the complete documentation index, see [llms.txt](/llms.txt).
# Integration Tips
Thanks to the versatility of our solution and hundreds of algorithms in our stack Recombee can be utilized in a wide variety of areas. You can use Recombee for recommending almost any type of content or product: videos, articles, fashion, real-estate, podcasts, jobs ... you name it :)
Every domain has its specifics and the following sections present some of the best practices for the correct use of our recommendation service.
---
**Choose your domain**
[Content Recommendations: videos, news, articles, music, etc.](#integration-tips-content)[Product Recommendations: e-commerce, classified advertising, etc.](#integration-tips-product)[Real Estate Recommendations: houses, apartments, land etc. for sale or rent](#integration-tips-real-estate)
---
## Content Recommendations
[Videos](#integration-tips-content-videos)[News & Articles](#integration-tips-content-articles)[Music & Podcasts](#integration-tips-content-music-and-podcasts)
### Videos
#### Items Catalog
* Each video (movie, series, asset) should be an _item_ in Recombee
* Typical [item properties](/getting_started#getting-started-catalog) are for example:
* title \[`string`\]
* categories/genres \[`set`\]
* description \[`string`\]
* languages \[`set`\]
* image \[`image`\] - for example a poster
* cast \[`set`\]
* tags \[`set`\]
* year \[`int`\]
* availability \[`boolean`\]
* minimal age of viewer \[`int`\]
* available since \[`timestamp`\]
* date of expiration \[`timestamp`\]
* is subscription needed \[`boolean`\] - for determining if the item is available for a particular user
* type \[`string`\] - determines if the item is a _movie_, _series_, _episode_, etc.
##### Modeling Series
Items in the catalog may be organized into [**Series**](/api/series), expressing an explicit, known ordering of items where applicable. Typical examples of series include consecutive TV show episodes, book titles, or podcast episodes.
The hierarchy can be either **one-level** (_series → episodes_) or **multi-level** (_series → seasons → episodes_), depending on the structure of your content.
* **Step 1: Upload episodes and series as Items**
Model every **episode**, **season**, and **series** as an _Item_ with the appropriate item properties (e.g., title, director, release date, etc.).
* **Step 2: Set hierarchy**
Use the [Insert to Series](/api/series#insert-to-series) endpoint to organize the Items into a series hierarchy.
* For a **series → season** link, set [itemType](/api/series#insert-to-series-param-itemType) \= `series`.
* For a **series/season → item** link, set [itemType](/api/series#insert-to-series-param-itemType) \= `item`.
* The [time](/api/series#insert-to-series-param-time) parameter defines the ordering within the series and should correspond to the season or episode number.
**Example:**
* _For each season_:
```
InsertToSeries (seriesId = "",
itemType = "series",
itemId = "",
time = "")
```
* _For each episode_:
```
InsertToSeries (seriesId = "",
itemType = "item",
itemId = "",
time = "")
```
The [Video Logics](/logics/video) have built-in support for handling Series (e.g., recommending newly published episodes, recommending next episode, etc.).
#### Interactions
* Send a [detail view](/api/interactions#request-add-detail-view) whenever a user clicks a video thumbnail
* Set a few important milestones in the video (e.g. 15%, 50%, 75%) and send a [view portion](/api/interactions#request-set-view-portion) whenever the user watches the video until a milestone
* It is very common to send a [purchase](/api/interactions#request-add-purchase) when you consider the movie to be consumed by the user (e.g. the user watched it until 90%)
* If users can bookmark or rate the items, send[bookmarks](/api/interactions#request-add-bookmark) and[ratings](/api/interactions#request-add-rating)
* Likes should be modeled as positive[ratings](/api/interactions#request-add-rating) (e.g. with rating `1.0`)
Don't forget to provide the _recommId_ parameter if the interaction is based on the recommendations. It will[give you very precise insight](/admin_ui#success-metrics-kpi) into the success of the recommendations in the Admin UI.
#### Scenarios
[Video Recipes: Discover how to personalize various use cases within your video platform.](/recipes/video)
### News & Articles
#### Items Catalog
* Each article should be an _item_ in Recombee
* Typical[item properties](/getting_started#getting-started-catalog) are for example:
* title \[`string`\]
* categories \[`set`\]
* tags \[`set`\]
* published \[`boolean`\]
* url \[`string`\]
* lead paragraph \[`string`\]
* image \[`image`\]
* expire date \[`timestamp`\]
* is paid content \[`boolean`\]
* author \[`string`\]
#### Interactions
* Send a [detail view](/api/interactions#request-add-detail-view) whenever a user opens an article.
* If users can rate the items, send[ratings](/api/interactions#request-add-rating). Likes should be modeled as positive[ratings](/api/interactions#request-add-rating) (e.g. with rating `1.0`).
* Don't forget to provide the _recommId_ parameter if the interaction is based on the recommendations. It will[give you very precise insight](/admin_ui#success-metrics-kpi) into the success of the recommendations in the Admin UI.
* Optional enhancement: Set a few important milestones in the article (e.g. 30%, 50%, 75%) and send a[view portion](/api/interactions#request-set-view-portion) whenever the user reads (scrolls) up to the portion
#### Scenarios
[News Recipes: Discover how to personalize various use cases within your news platform.](/recipes/news)
### Music & Podcasts
#### Items Catalog
* Each song should be an _item_ in Recombee
* Typical[item properties](/getting_started#getting-started-catalog) are for example:
* title \[`string`\]
* artist \[`string`\]
* genre \[`string`\]
* featured artists \[`set`\]
* labels \[`set`\]
* album title \[`string`\]
* album cover \[`image`\]
* country \[`string`\]
* release date \[`timestamp`\]
* is explicit \[`boolean`\]
* duration \[`int`\]
#### Interactions
* Set a few important milestones in the song (e.g. 15%, 50%, 75%, 100%) and send a[view portion](/api/interactions#request-set-view-portion) whenever the user listens to the song until a milestone
* Send us [ratings](/api/interactions#request-add-rating)with the _rating_ set to `1.0` for liked songs
* Send us [ratings](/api/interactions#request-add-rating)with the _rating_ set to `-1.0` for disliked songs
#### Setting Up Recommendations
* Create a [scenario](/scenarios) for each place you want to show the recommendations.
* Set [filters](/reql) to the scenarios: At least a filter for recommending only available items should be set.
If the availability is based on the release date, the filter can look like this:
ReQL
```
'release_date' < now()
```
In many cases, you also need to show only appropriate content to minors. If you set a[user property](/api/user-properties) `is_minor` to _true_ for the minors, then the filter can look like this:
ReQL
```
if context_user["is_minor"] then
not 'is_explicit'
else
true
```
Such filter rules can be added to the[Global Settings](/scenarios/settings-in-admin-ui#global-settings), so they are applied to all your scenarios.
#### Scenarios
* Create a [scenario](/scenarios) for each place you want to show the recommendations.
##### Songs / Podcasts for You
To obtain a personalized list of the top songs or podcasts for a user call the[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with the _recombee:personal_ [Logic](/logics).
##### New Releases
To obtain a personalized list of the recently added songs or podcasts that shall be interesting for the user, call the[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with the _recombee:personal_ [Logic](/logics) and add the_Recent items_ [predefined Filter rule](/scenarios/settings-in-admin-ui#filters).
##### Trending Songs / Podcasts
To obtain songs or podcasts that are currently globally popular, use[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with the _recombee:popular_ [Logic](/logics).
* You can choose what time period will be taken into consideration when evaluating the most popular songs using the_timePeriod_ parameter of the Logic (value is in seconds)
* The currently popular content can often vary in different countries. If you upload the user's _country_ as the[user property](/api/user-properties), you can get the content popular among users from the same country by setting _userSegmentFilter_ parameter of the Logic to:
ReQL
```
'country' == context_user["country"]
```
##### Related Songs or Podcasts
In order to obtain songs that are related to a particular song, call the[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with the _recombee:similar_ [Logic](/logics).
You can use these songs e.g. for the autoplay, so it keeps the mood of the song the user is currently listening to.
##### Top Artists / Podcasters for You
Based on the listened songs, Recombee can recommend interesting artists for the user.
* First, create an[Item Segmentation](/segmentations) on the [item property](/getting_started#getting-started-catalog) that contains the primary artist
* Then go to the [Scenarios](/segmentations) section and create a scenario of the[Recommend Item Segments To User](/api/recommendations#request-recommend-item-segments-to-user) type based on the created _artists_Segmentation
Requesting this scenario will give you the artists that shall be the most interesting for a particular user.
##### Related Artists / Podcasters
You can show the related artists on an artist's detail page.
* If you don't have an[Item Segmentation](/segmentations)based on the primary artist yet, create one
* Then go to the [Scenarios](/segmentations) section and create a scenario of the[Item Segments To Item Segment](/api/recommendations#request-recommend-item-segments-to-item-segment) with both Context and Result Segmentations set to the_artists_ Segmentation
Requesting this scenario with _segmentId_ set to a particular artist will give you the artists related to that artist.
##### Top Albums for You
Based on the listened songs, Recombee can recommend albums that shall be interesting for the user.
* First, create an[Item Segmentation](/segmentations) on the [item property](/getting_started#getting-started-catalog) that contains the album title or ID
* Then go to the [Scenarios](/segmentations) section and create a scenario of the[Recommend Item Segments To User](/api/recommendations#request-recommend-item-segments-to-user) type based on the created _albums_Segmentation
Request this scenario to get the top albums for the user.
## Product Recommendations
### Items Catalog
* Each product that you want to recommend should be an _item_ in Recombee.
* Typical[item properties](/getting_started#getting-started-catalog) are for example:
* title \[`string`\]
* image link \[`image`\]
* available \[`boolean`\]
* categories \[`set`\]
* price \[`double`\]
* url \[`string`\]
* brand / vendor \[`string`\]
* on sale \[`boolean`\]
Then there are various segment-specific properties, for example in fashion:
> * gender \[`string`\]
> * material \[`string`\]
> * color \[`string`\]
> * available sizes \[`set`\]
Tip
You can set a [catalog feed](/catalog_feeds) (e.g. Google Merchant Feed) in the Admin UI for products catalog synchronization
#### Handling Variants
* If your products come in multiple variants (sizes, colors), the preferred representation in most cases is to have the master product as an item in Recombee and send interactions to it from pages of all its variants.
* If you want to ensure compatibility of available product sizes and user's preferred sizes, model both as item/user properties and use filter like this one:
ReQL
```
context_user["sizes"] == null OR size('available_sizes' & context_user["sizes"]) > 0
```
* In the case of having each variant as an item in Recombee, the recommendations will also work, but it may take longer to train the models properly at lower traffic sites as the number of interactions is divided between all the variants.
### Interactions
* Send a [detail view](/api/interactions#request-add-detail-view) whenever a user views a detail page of a product
* Send a [cart addition](/api/interactions#request-add-cart-addition) whenever a user adds a product into the cart
* Send a [purchase](/api/interactions#request-add-purchase) whenever a user buys a product.
* There will be an[Add Purchase request](/api/interactions#request-add-purchase) per each product in the ordered cart. Optionally, these requests can be sent inside a single[Batch request](/api/miscellaneous#request-batch).
* Set the `price` parameter to see revenue based on recommendations in the [Admin UI](/admin_ui).
* If users can bookmark or rate the items, send[bookmarks](/api/interactions#request-add-bookmark) and[ratings](/api/interactions#request-add-rating)
* It is suggested to provide the _recommId_ parameter if the interaction is based on the recommendations.
It will [give you very precise insight](/admin_ui#success-metrics-kpi) into the success of the recommendations in the Admin UI.
### Scenarios
[E-commerce Recipes: Discover how to personalize various use cases within your e-commerce site.](/recipes/e-commerce)
## Real Estate Recommendations
### Items Catalog
* Each property (building, apartment, ...) that you want to recommend should be an _item_ in Recombee.
* Typical[item properties](/getting_started#getting-started-catalog) are for example:
* title \[`string`\]
* image link \[`image`\]
* available \[`boolean`\]
* url \[`string`\]
* state \[`string`\]
* city \[`string`\]
* neighborhood \[`string`\]
* zip code \[`string`\]
* latitude \[`double`\]
* longitude \[`double`\]
* price \[`double`\]
* description \[`string`\]
* square feet \[`int`\]
* number of bedrooms \[`int`\]
* number of bathrooms \[`int`\]
* parking spaces \[`int`\]
* pets allowed \[`boolean`\]
* year built \[`int`\]
* type \[`string`\] - _apartment_ / _family house_ / _condo_ / ...
* amenities \[`set`\] - e.g. _air condition_, _balcony_, _fire place_, _swimming pool_ ...
### Interactions
* Send a [detail view](/api/interactions#request-add-detail-view) whenever a user views a detail page of a property
* Send a [bookmark](/api/interactions#request-add-bookmark) whenever a user bookmarks a property
* Send a [purchase](/api/interactions#request-add-purchase) when a user expresses a strong interest in the particular property - e.g. makes an offer or books a tour.
* Don't forget to provide the _recommId_ parameter if the interaction is based on the recommendations. It will[give you very precise insight](/admin_ui#success-metrics-kpi) into the success of the recommendations in the Admin UI.
### Setting Up Recommendations
* Create a [scenario](/scenarios) for each place you want to show the recommendations.
* Into the [Global Settings](/scenarios/settings-in-admin-ui#global-settings) add a filter to allow only available properties to be recommended. You can pick predefined rule _Available items_ from the _Recombee Business Rules Library_.
### Scenarios
#### Properties in User-Specified Area
* After a user inserts the area where the user is looking for a property the best deals for the user in the area will be delivered by Recombee
* Use[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with _recombee:homepage_ [Logic](/logics) in that case
* The area inserted by the user should be sent in the `filter`parameter of the[Recommend Items To User request](/api/recommendations#request-recommend-items-to-user) in order to allow only properties from the particular area. It can look like:
ReQL
```
'state'=="TX" and 'city'=="Austin"
```
* Alternatively, you can store the user's area to Recombee as[user properties](/api/user-properties), and use filter like:
ReQL
```
'state' == context_user["state"] and 'city' == context_user["city"]
```
#### Properties in a Geolocation
* If the user browses a map, you can show (or highlight) the most fitting properties for the user (according to the user's past interactions).
* Use[Recommend Items To User](/api/recommendations#request-recommend-items-to-user) endpoint with _recombee:personal_ [Logic](/logics)
* Set the request's `filter` parameter to allow only properties in the map radius. You can use [earth\_distance](/reql/functions/geographical#reql-func-earth-distance) ReQL function to achive this.
ReQL
```
earth_distance('latitude', 'longitude', , < centre of the map longitude> ) <