NextJS Sitecore Dictionary


When building components it happens that we need a text that is not really context specific. I generally encourage to create context specific buttons as it can give a better SEO and more user friendly site, eg. link text “See more about Sitecore JSS” instead of just “See more”.

However it still happens that we need some text and of course we need to be able to translate it and update with content. Sitecore have implementation and API available for dictionary items1, so when creating your SXA site you will have a Dictionary site level folder where folders and phrases can be added.

The Sitecore head template - the connecting parts

Sitecore provides a template for starting a NextJS based head, it is the one you get when creating a new XM Cloud project in a new repository. The template contains a DictionaryService2 that handles fetching the phrases.

The catch-all page implementation in pages/[[..path]].tsx handles to set several additional properties available on components, one of them is dictionary. It is handled through a PagePropsFactory which have several plugins and the NormalModePlugin3 fetches dictionary phrases and exposes this property.

Using phrases in components

The dictionary is exposed with PagePropsFactory so it is available in _app.tsx but not on the individual components.

We expose the dictionary items by using next-intl package in _app.tsx.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import { NextIntlClientProvider } from 'next-intl';

export default function App({ Component, pageProps, router }: AppProps<SitecorePageProps>): JSX.Element {
  const { ...rest } = pageProps;
  return (
    <NextIntlClientProvider messages={pageProps.dictionary} locale={pageProps.locale}>
      <Component {...rest} />
    </NextIntlClientProvider>
  );
}

Hereby we can in a component use those phrases:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
export const FactBox = (props: FactBoxProps): JSX.Element => {
    const t = useTranslations();

    return (
      <div className="fact" key="Author">
        <span>{t('Author')}: </span>
        <Text field={props?.fields?.Author} tag="span" />
      </div>
    );
}