Using Sitecore Search in NextJS site


Expose data for indexing

The simplest way to use Sitecore Search is by crawling the website, in the Sitecore Search Introduction the various methods are presented.

You need to have the necessary information exposed on the site. NextJs have a neat <Head> component that allows you to add meta tags to the head html tag, even from a component inserted on the page.

Example product.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
export const Default = (props: ComponentProps): JSX.Element => {
  const data = useComponentProps<ProductData>(props.rendering.uid);

  return (
    <>
      <Head>
        <meta name="product_id" content={data?.productId} />
        <meta property="og:image" content={data?.mainImage?.href} />
      </Head>
      <div>
        <h2>{data?.name}</h2>
        <img
          src={data?.mainImage?.href}
          width={data?.mainImage?.width}
          height={data?.mainImage?.height}
          alt={data?.alt ?? `Image of product {data?.name}`}
        />
      </div>
    </>
  );
};

Configure indexer

You need configure the indexer in Sitecore Search to include the data in the desired attribute in the Document Extractors part.

Sitecore Search configuration of attribute with expression

Components on pages

In Sitecore Search: React UI you can see how to use the SDK to generate client side components for search.

Search also provides a nice REST based api. With that you can make SSR and SSG pages based on search content.