# Programmatic JavaScript and TypeScript

> Current Froomle documentation · [View canonical page](https://docs.froomle.com/froomle-doc-main/v2/js_lib/programmatic.html)

Use this path when your JS/TS code fetches recommendations and renders the cards. Start with [initializing SDK state](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#MinInit), connect [consent](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#cmp-bridge), then request a list or batch of slots. Use [explicit events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) for the cards you render.

<a id="Programmatic"></a>

## Programmatic API (JS/TS)

Use programmatic mode when markup placeholders are not enough. Typical cases:

-   You want to fetch recommendations before rendering UI.
    
-   You want explicit batching control across multiple requests.
    
-   You render custom UI and must send events manually.
    

No `data-froomle-…​` placeholders are required in this mode.

For benchmark-specific request and rendering patterns, see [Benchmarking and A/B Testing with the SDK](https://docs.froomle.com/froomle-doc-main/v2/js_lib/benchmarking.html#BenchmarkingSdk).

> **NOTE:**
> 
> For setter scope, see [Runtime Scope Guide](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#RuntimeScope). Programmatic integrations still use shared page/app-level SDK state (`setEnvironment`, `setPageVisit`, `setChannel`, optional `setSiteContext` override or clear, `setSubscriptionLevel`, `setConsent`, `setDeviceId`, `setUserId`, `setContextItem`, `setContextItemType`), while list/filter/request arguments are supplied per API call.

> **TIP:**
> 
> Need a full runnable project for this mode? Use [frontend-sdk-examples](https://bitbucket.org/froomle/frontend-sdk-examples) for programmatic JS/TS and retail-oriented examples.

How it works:

1.  Configure SDK state (`setEnvironment`, `setPageVisit`, optional `setSiteContext` override, `setSubscriptionLevel`, consent, identity).
    
2.  Call `trackCurrentPage()` explicitly for the current page, including after late consent when your application chooses to track it. Use business-event helpers or `sendEvent(…​)` for other event types.
    
3.  Request recommendation items (`getRecommendations`, `smartSort`, or proxy flow).
    
4.  Render with your own UI code.
    
5.  If your application renders the finished cards, send [recommendation events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) explicitly.
    

<a id="_request_models"></a>

### Request Models

Choose the API based on what your code needs to render:

| API | Use it when |
| --- | --- |
| [`getRecommendations(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/programmatic.html#programmatic-lists) | You render one or more lists and decide what to show based on each list’s `experience`. |
| [`proxyReco(…​)` and `fulfillRecommendations()`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/programmatic.html#programmatic-slots) | Each card requests one slot. Queue the slots, then explicitly send them as a batch. |

<a id="programmatic-lists"></a>

### Programmatic list requests

Call `getRecommendations(…​)` with one entry per list. Each entry supplies `list_name`, `limit` (how many items to return initially), and `list_size` (how many to rank). Set optional `showFroomleContentFor` on a list entry to override that list’s content policy without changing the visitor’s assignment.

Each row in `response.lists()` has an `experience` that tells you what to render. It is not the visitor’s group name. The SDK uses the same two values even when your integration uses custom group names:

-   `experience: 'customer'`: render your original CMS content. The SDK returns `items: []`, no cache key, and no pagination helper, even if the API returned items.
    
-   `experience: 'froomle'`: render the returned items. An empty array here is a successful empty result, not a switch to customer content.
    

For example, if your groups are `variant_a` and `variant_b` and a list has `showFroomleContentFor: ['variant_b']`, that list returns `experience: 'froomle'` for `variant_b` and `experience: 'customer'` for `variant_a`. The visitor’s group does not change.

> **TIP:**
> 
> Using custom benchmark groups
> 
> Agree with Froomle on the exact group names and which lists need to return recommendations for those groups. `showFroomleContentFor` controls frontend rendering; it does not change the backend configuration.
> 
> The SDK applies the list policy, but your application renders the cards. Follow the returned `experience` instead of branching on the group name or checking whether `items` is empty.

A rejected request returns no experience. Handle startup, benchmark contract, or request failures separately.

This example uses the list’s configured policy. The render and error callbacks belong to your application.

```ts
import { getRecommendations } from '@froomle/frontend-sdk'

const listName = 'recommended_for_you'
try {
  const response = await getRecommendations([
    { list_name: listName, limit: 4, list_size: 4 },
  ])
  const [list] = response.lists()
  const attribution = { list_name: listName, request_id: response.request_id }
  if (list.experience === 'customer') {
    renderOriginalCards(attribution)
  } else {
    renderRecommendations(list.items, attribution)
  }
} catch (error) {
  handleRecommendationError(error)
}
```

`response.items()` flattens the selected recommendation items across the lists; it does not include items from customer-experience lists. Use `lists()` if you need to make a rendering decision per list. Each recommendation item exposes `Id`, `Rank`, `RequestId`, and `UserGroup`. Read content fields such as `item.get<string>('title')` according to your recommendation setup.

<a id="_list_names_and_aliases"></a>

#### List names and aliases

The list name in the request identifies the policy and the placement for tracking. The response’s `list_name` is the returned name and may be an alias. For example, if you request `list_name: 'homepage_sports'` with `alias: 'sports'` and the response names that row `sports`, look up `sports`, not `homepage_sports`. Use `homepage_sports` for the policy and for explicit event attribution.

In TypeScript, use `response.lists().find(list ⇒ list.list_name === 'sports')`. JavaScript also supports `response.getItemsByListName('sports')`, which returns a list row or `null`; this helper is not in the package’s TypeScript declarations.

<a id="_request_fields"></a>

#### Request fields

Use each list entry for filters and custom list variables expected by your model, and the optional second argument for request-local `exclusions` or `autoExclusions`. Use `setCustomVariable(…​)` for shared custom recommendation fields. SDK-managed fields such as `device_id`, `user_group`, and `version` cannot be overridden through custom request fields. Configure identity and assignment via the SDK’s [runtime settings](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#RuntimeScope) instead.

> **TIP:**
> 
> Need full request payload rules (required fields, list structure, histories, batching)? See [Recommendation Request Model](https://docs.froomle.com/froomle-doc-main/v2/guide/topics/recommendation-requests.html).

<a id="ProgrammaticPagination"></a>

### Paginate a programmatic recommendation list

Request the full ranked list with `list_size` and the initial page with `limit`. A current Froomle-experience result with a usable key supports `pagination.getPage(pageNumber)`. Use `getListSlice({ listKey, offset, limit })` for a saved key or a different rank range.

See [Programmatic Pagination with the SDK](https://docs.froomle.com/froomle-doc-main/v2/js_lib/programmatic-pagination.html) for examples, cache expiry, and how to track displayed items.

<a id="SmartSortSdk"></a>

### Smart Sorting and Reranking with the SDK

Smart sorting now has a dedicated SDK page because the integration contract differs by rendering method. See [Smart Sorting and Reranking with the SDK](https://docs.froomle.com/froomle-doc-main/v2/js_lib/smart-sorting-reranking.html) for declarative DOM/script-tag, module/import DOM, programmatic JS/TS, React, backend-fetched, diagnostics, and troubleshooting guidance.

<a id="programmatic-slots"></a>

### Programmatic slot requests

Call `proxyReco(…​)` once per slot, then call `fulfillRecommendations()` to send the queued work. Do not await a handle before flushing. Each call asks for one item; compatible slots for the same list combine into a single list row. Different exclusions can require separate requests.

Set the optional `showFroomleContentFor` on the slot request to override the list policy. Slots sharing a list name must agree on that policy. Register any external group before the first recommendation operation; queuing a proxy counts, even before the flush.

The flush reports whether the queued requests succeeded. Each handle is a separate outcome:

-   A returned recommendation resolves to a `RecommendationItem`.
    
-   A customer-experience slot resolves to `null`. Your application decides which original card to show. If you also need the request ID for explicit tracking of original content, use [`getRecommendations(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/programmatic.html#programmatic-lists); a `null` slot result does not provide it.
    
-   A Froomle-experience slot with no item rejects with `No recommendation available`, even when `fulfillRecommendations()` succeeds. Other slots in the same batch can still resolve successfully.
    
-   A failed request rejects the flush and its affected handles.
    

```ts
import { proxyReco, fulfillRecommendations } from '@froomle/frontend-sdk'

const query = { list: 'recommended_for_you', filters: { categories: ['Sports'] } }
const slots = [proxyReco(query), proxyReco(query)]
const results = Promise.allSettled(slots)

try {
  await fulfillRecommendations()
} catch (error) {
  handleBatchError(error)
}

for (const [index, result] of (await results).entries()) {
  if (result.status === 'rejected') {
    handleSlotError(index, result.reason)
  } else if (result.value === null) {
    renderOriginalCard(index)
  } else {
    renderRecommendation(index, result.value)
  }
}
```

<a id="ExclusionsModule"></a>

## Global auto-exclusion defaults

Module integrations can set a default auto-exclusion config once:

```ts
import { setAutoExclusions } from '@froomle/frontend-sdk'

setAutoExclusions(true) // default source: [data-froomle-id]
```

Or configure one or more custom sources:

```ts
setAutoExclusions({
  sources: [
    {
      selector: '[data-article-id]',
      idAttribute: 'data-article-id',
      itemType: 'article'
    }
  ]
})
```

The default config applies to later DOM, programmatic, and React recommendation requests. Passing `autoExclusions` on an individual request overrides the default for that request. For example, `autoExclusions: false` disables the selector scan for that request without clearing manual exclusions.

<a id="ExclusionsManualProgrammatic"></a>

## Manual and Programmatic Exclusions

Manual persistent exclusions apply to later recommendation requests until cleared:

```ts
import { addExclusions, clearExclusions } from '@froomle/frontend-sdk'

addExclusions([
  'sample_item_id_1',
  { id: 'sample_item_id_2', item_type: 'video' },
  { id: 'sample_item_id_3', itemType: 'podcast' }
])

// Later, when the exclusion scope no longer applies:
clearExclusions()
```

Request-level exclusions apply only to one recommendation request:

```ts
import { getRecommendations } from '@froomle/frontend-sdk'

await getRecommendations([
  { list_name: 'recommended_for_you', limit: 4, list_size: 4 }
], {
  exclusions: [
    { id: 'already-visible-article', item_type: 'article' }
  ]
})
```

Programmatic auto-exclusions scan the current DOM at request time:

```ts
import { getRecommendations } from '@froomle/frontend-sdk'

await getRecommendations([
  { list_name: 'recommended_for_you', limit: 4, list_size: 4 }
], {
  autoExclusions: {
    enabled: true,
    sources: [
      {
        selector: '[data-article-id]',
        idAttribute: 'data-article-id',
        itemType: 'article'
      }
    ]
  }
})
```

When using `getRecommendations(…​)` directly, the SDK shapes the recommendation request but does not own your rendering. If you render the cards yourself, send [recommendation events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) explicitly using the displayed item’s identity and the original response’s request ID.
