Context mapping with Headless
Context mapping with Headless
If you have configured context mappings on a tracking ID, you can use the setCustom method on the Context controller to specify custom context values at query time.
Context mappings let you extend the default context object in Commerce API requests with custom fields.
Each mapping defines a key, a data type, and one or more destinations that control where the Commerce API routes the value, such as the query pipeline context, Coveo ML context, or field aliases.
|
|
Type definitions
|
Prerequisites
Before using setCustom, you must create context mappings on your tracking ID using the Context Mappings API.
The Commerce API validates each value you send against its configured type and silently drops any key that doesn’t match.
Example context mappings
The following examples assume the target tracking ID has been configured with these context mappings, expanding on the List context mappings example in the documentation:
[
{
"key": "fitmentProducts",
"type": "PRODUCT_LIST",
"destinations": [{"attribute": "QUERY_PIPELINE_CONTEXT"}]
},
{
"key": "shoppingIntent",
"type": "STRING",
"destinations": [
{"attribute": "ML_CONTEXT"},
{"attribute": "QUERY_PIPELINE_CONTEXT"}
]
},
{
"key": "storeId",
"type": "STRING",
"destinations": [
{
"attribute": "FIELD_ALIASES",
"fieldAlias": "price_dict",
"fieldSource": "price_dict.{{contextValue}}"
}
]
},
{
"key": "contractCustomer",
"type": "BOOLEAN",
"destinations": [{"attribute": "QUERY_PIPELINE_CONTEXT"}]
},
{
"key": "loyaltyTier",
"type": "NUMBER",
"destinations": [{"attribute": "QUERY_PIPELINE_CONTEXT"}]
}
]
| Key | Type | Destinations | Typical use case |
|---|---|---|---|
|
|
|
Filter results to compatible parts via a pipeline filter rule. |
|
|
|
Influence ML relevance and enable intent-based ranking expressions. |
|
|
|
Resolve store-specific pricing from a dictionary field. |
|
|
|
Apply contract-specific pricing or catalog rules. |
|
|
|
Boost results or unlock promotions based on loyalty level. |
Context value retrieval
The values you pass to setCustom depend on the context mapping type and your application’s runtime state.
-
STRINGvalues likeshoppingIntentare typically derived from the section of the site the user is browsing (for example, a category page) or from an explicit user selection. -
STRINGvalues likestoreIdoften come from a user preference stored in a cookie or session, such as a selected store location. -
PRODUCT_LISTvalues likefitmentProductsare usually derived from user interactions (for example, a vehicle selector that resolves to compatible part SKUs) or from product recommendations. -
BOOLEANvalues likecontractCustomerare typically resolved from authentication state or user profile data. -
NUMBERvalues likeloyaltyTiermay come from a CRM or loyalty system.
Set custom context at query time
Call setcustom on the Context controller before dispatching a search action.
The controller automatically includes the custom context in all subsequent Commerce API requests.
JavaScript example
The following is a complete vanilla JavaScript example that demonstrates setCustom with the context mappings above.
|
|
Type definitions
|
// engine.js
import {
buildCommerceEngine,
buildContext,
buildSearch,
getSampleCommerceEngineConfiguration,
loadSearchActions,
} from 'https://static.cloud.coveo.com/headless/v3/commerce/headless.esm.js';
import {renderSearchResults} from './renderSearchResults.js';
const coveoHeadlessCustomContext = () => {
const intentSelect = document.getElementById('shopping-intent');
const storeSelect = document.getElementById('store-id');
const fitmentTextarea = document.getElementById('fitment-products');
const contractSelect = document.getElementById('contract-customer');
const loyaltySelect = document.getElementById('loyalty-tier');
const applyButton = document.getElementById('apply-context');
const contextStateEl = document.querySelector('#context-state pre code');
const searchResultsEl = document.getElementById('search-results');
const engine = buildCommerceEngine({
configuration: getSampleCommerceEngineConfiguration(),
});
const contextController = buildContext(engine);
const searchController = buildSearch(engine);
const {executeSearch} = loadSearchActions(engine);
searchController.subscribe(
() => renderSearchResults(searchResultsEl, searchController.state.products)
);
contextController.subscribe(() => {
const {custom, ...rest} = contextController.state;
contextStateEl.textContent = JSON.stringify({...rest, custom}, null, 2);
});
applyButton.addEventListener('click', () => {
const customContext = {
...contextController.state.custom,
shoppingIntent: intentSelect.value,
storeId: storeSelect.value,
fitmentProducts: fitmentTextarea.value.split(',').map((s) => s.trim()),
contractCustomer: contractSelect.value === 'true',
loyaltyTier: Number(loyaltySelect.value),
};
contextController.setCustom(customContext);
engine.dispatch(executeSearch());
});
};
document.addEventListener('DOMContentLoaded', coveoHeadlessCustomContext);
Details
| This configuration doesn’t have context mapping defined, meaning changing values for the context mapping elements won’t affect the returned results. | |
| Dispatch updates to a render function when the search controllers received updates. | |
| This is just for demonstration purposes. In a real-world implementation, displaying the values of the context being passed would not add value. | |
setCustom replaces the entire custom object each time it is called. To preserve previous values while updating a single key, spread the existing contextController.state.custom values into your new object. |
|
| Refer to Determine suitable values for examples on how to derive real world examples. | |
| Set the values for context mapping before dispatching the search action to ensure the search results reflect the updated user intent. |
Set custom context at engine initialization
You can also provide initial custom context values when building the commerce engine, through the context.custom property of the engine configuration.
import {
buildCommerceEngine,
getSampleCommerceEngineConfiguration,
} from '@coveo/headless/commerce';
export const engine = buildCommerceEngine({
configuration: {
...getSampleCommerceEngineConfiguration(),
context: {
language: 'en',
country: 'US',
currency: 'USD',
view: {
url: 'https://my-store.example.com',
},
custom: {
shoppingIntent: 'fishing',
storeId: '10010',
fitmentProducts: ['SP-00301', 'SP-01202'],
contractCustomer: true,
loyaltyTier: 3,
},
},
},
});
Values set at initialization are included in all Commerce API requests from the start.
Use setCustom to update them dynamically as the user navigates or interacts with your application.