Breaking It Down
Let's say you want to use Coveo Recommendations. Before you're able to do that you need to have some form of Coveo Analytics running from within your NextJs app and providing that information to the Recommendations model. Without that, it just won't work. To make it work we've broken it down into two sections. The first being loading the script and the second sending the pageview
events.
Load Coveo Analytics
Let's create a NextJs component that loads in the Coveo Analytics JavaScript file in the <head>
element.
import Script from 'next/script';
const CoveoAnalytics = (): JSX.Element => { return ( <> <Script id="coveouasetup" strategy="beforeInteractive" src="https://static.cloud.coveo.com/coveo.analytics.js/2/coveoua.js" /> ... </> ); }; export default withDatasourceCheck()<CoveoAnalyticsProps>(CoveoAnalytics);
The above code creates a <script>
tag to load in the Coveo Analytics JS from whatever location you choose.
Setup a Page View Event
In the same component (or elsewhere if you are so included), we're going to run another component in the footer that pushes the page view events.
<CoveoAnalyticsTrack />
But what does that component look like? Somewhat similar to traditional Js such that we can grab the current page. You could grab other information from Sitecore context if so inclined.
const CoveoAnalyticsTrack = (): JSX.Element => { const [url, setUrl] = React.useState<string | null>(null);
useEffect(() => { setUrl(window.location.origin); }, []); return ( <script id="coveoanalytics" key="coveoanalytics" dangerouslySetInnerHTML={{ __html:
document.addEventListener("DOMContentLoaded", function(){ coveoua('init', 'xxxxx-xxxx-xxxxx-xxxxx'); // access token coveoua('send', 'pageview', { contentIdKey: 'uri', contentIdValue: ${url}, }); });
, }} /> ); }; export default withDatasourceCheck()<CoveoAnalyticsProps>(CoveoAnalyticsTrack);
We're going to load up this component in our footer placeholder so that it is loaded near the end of the page. Because we are using the useEffect()
to grab the URL using the window
object and set it in the state.
This way it will re-render the script
tag when the url
becomes available. And that's all that's needed. With this we've got page views being added to the model.