Improve Coveo Headless Search Synchronizing Url Parameters

Example Subheading

September 18, 2022

By David Austin

Why Do We Need To Maintain Search State In Url Parameters?

Is a question you might be asking yourself. This might not even be a requirement from your client but by doing so improves the usability and accessibility of your search implementation. Not only is one of the benefits of ensuring that a search query is updated in the Url is that users can then bookmark it; it can also provide deep linking alternatives from elsewhere on the site to conduct searches. Not to mention, a user could create a simple search box that simply tacks an input field's value onto the Url and have it conduct a search.

If nothing else, it's also another good visual indicator that the query has changed from an accessibility perspective.

The Code

In order to make this work in CoveoΒ Headless we thankfully have more than one option. We can either use the buildUrlManager or the buildSearchParameterManager. The former being the faster of the two and the one I'm going to use today.

In our ResultList component's useEffect we're going to add the following code fragment.


  useEffect(() => {
    // Identify the hash fragment
    const fragment = window.location.hash.slice(1);
// Build the UrlManager controller with said fragment.
const urlManager = buildUrlManager(engine, {
  initialState: { fragment },
});

// Update the state
urlManager.subscribe(() => {
  const hash = `#${urlManager.state.fragment}`;
  history.pushState(null, document.title, hash);
});

// Synchronize the has with the latest fragment.
window.addEventListener('hashchange', () => {
  const fragment = window.location.hash.slice(1);
  urlManager.synchronize(fragment);
});

...

}, []);

Once this has been added you can then use a regular link with the search#q=technology&f[filetype]=pdf on the search page and you should see the query update accordingly. It doesn't take much to do and yet it's extremely handy. Now not only can people bookmark the link, but people can perform other deep linking features from within your site. You'll also notice that facets work in a similar fashion as well.

Image of Fishtank employee David Austin

David Austin

Development Team Lead | Sitecore Technology MVP x 3

David is a decorated Development Team Lead with Sitecore Technology MVP and Coveo MVP awards, as well as Sitecore CDP & Personalize Certified. He's worked in IT for 25 years; everything ranging from Developer to Business Analyst to Group Lead helping manage everything from Intranet and Internet sites to facility management and application support. David is a dedicated family man who loves to spend time with his girls. He's also an avid photographer and loves to explore new places.