Navigating between pages
Navigating between pages
This is for:
DeveloperWhen building your commerce interfaces, it’s crucial to manage the state of the current URL using Headless.
Use Headless to send the URL information with every Commerce API request, ensuring that actions affecting the view—such as navigating to a new page—emit the correct analytics events.
This is also important for product listing pages because you need to specify the URL that corresponds to the PLP configuration you want to target.
Setting view on engine initialization
When initializing the commerce engine, you can set the URL by using the context.view
object.
import { buildCommerceEngine } from '@coveo/headless/commerce';
import { loadCartItemsFromLocalStorage } from '../utils/cart-utils';
export const getEngine = () => {
if (_engine !== null) {
return _engine;
}
_engine = buildCommerceEngine({
configuration: {
organizationId: '<ORGANIZATION_ID>',
accessToken: '<ACCESS_TOKEN>',
analytics: {
trackingId: '<TRACKING_ID>'
},
context: {
currency: '<CURRENCY>',
country: '<COUNTRY>',
language: '<LANGUAGE>',
view: {
url: '<URL>'
},
}
cart: {
items: loadCartItemsFromLocalStorage() ?? [],
},
},
});
return _engine;
};
Set the view URL to the current page URL. |
Modifying the view on page change
When the user navigates to a new page, you must update the view URL using the Context
controller.
import { engine } from './Engine';
import { buildContext } from '@coveo/headless/commerce';
const context = buildContext(engine);
onPageChange(newUrl: string) {
context.setView({ url: newUrl });
}
Initialize the Context controller by passing in the previously initialized engine. |
|
Call the setView method on the Context controller to change the url when the user navigates to a different page. |
For more details on how to set the URL in a sample project, see the sample in the Headless repository