XM Cloud and Sitecore Search - Dynamic Wild Card Page Data
Summary
Recently, we had a project with thousands of Provider records in an external system. We had already built a Provider search using Sitecore Search in our headless Next.js application, but we needed a way to present each record's details dyanimically on a detail page.
For example:
www.website.com/providers/12345
and www.website.com/providers/67890
All of the Provider data was already in Sitecore Search (we cralwed an api source), so we decided to leverage a wild card data approach and pull that data directly.
This blog post walks through our approach in a simplified way to demonstrate the concept.
The Solution
First, we confirm what data is in our schema and present in Sitecore Search. In this example, this is the data that we want to show on our Provider detail page:
Next, we need to set up our Wildcard *
page in XM Cloud so that Sitecore knows that we have a dynamic data page:
We want: www.website.com/providers/12345
, with 12345
being the npi number (or any unique id) of a given provider.
Please note that we could have handled the entire route outside of Sitecore in the Next.js application. We decided to keep it in Sitecore as we leverage Dictionary Items, Configurations and other content from the CMS in addition to the dynamic Provider page data.
Next, we modify the [[…path]].tsx
so that we know when to handle a provider path with a valid npi number.
We look for our slug path providers
and then check to see if an npi number is matched in the url. If there is a match then we know that we want a wild card page.
We set context to the providers page followed by the wild card (,-w-, in Next.js
).
See the code below:
The page loads and we still have the npi in our url to leverage further down the line, but all the page context is now coming from the wild card *
page in Sitecore.
The wild card *
page will have a providers detail
component on it. This component will have logic to take the npi number and query Sitecore Search:
This calls an internal api route:
The internal api then leverages the Sitecore Search REST api. Sees documentation shere (opens in a new tab) to read up more on authentication and best practices.
In our example, we take the npi numbder out of the url and then send it to the api to return the matching record. See the following code:
Once the results are returned you can continue to use them as you would any other props or data in your component.
Conclusion
Sitecore Search provides flexible and easy to use REST apis to help leverage the data in your search index. In this example, we were able to use an already built Sitecore Search experience and reuse the data to dyanimcally render details on our detail pages without much additional overhead.