Getting data outside of the page layout using Sitecore GraphQL API

There will be cases when the data passed don’t actually change that often and because of that we would want to get this data from outside of the home item or somewhere from global location. This is where Next.js API Routes will come into the picture. Next.js has introduced a feature which allows creating API routes within Next.js without having to rely on backend integration. 


I had the requirement to get the data from the global item in the Layout.tsx so I tried to create the GraphQLRequestClient but it is not allowed and gave me the error as:

graphql_request__WEBPACK_IMPORTED_MODULE_0__.GraphQLClient is not a constructor

So I got the link https://www.getfishtank.com/insights/utilizing-nextjs-api-routes-for-sitecore-xm-cloud-graphql-queries that helped me a lot. You can follow this for more detail but on high level I will mention how can we achieve to get the global data in the Layout.tsx file.

So below are the high level steps

  1. Create an API in next js app, as graphql query can access the data in the API
  2. Use that API's response in the Layout.tsx and do your logic what you want to achieve.

  1. Create an API in next js app, as graphql query can access the data in the API
In the path \src\sxastarter\src\pages\api\ create a file (this file name will be api endpoint) getglobalitemsetting.ts and paste the following code.

import { gql, GraphQLClient } from 'graphql-request';
import type { NextApiRequest, NextApiResponse } from 'next';
import config from 'temp/config';

const getGlobalItemSettingApi = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
    const graphQLClient = new GraphQLClient(config.graphQLEndpoint);
    graphQLClient.setHeader('sc_apikey', config.sitecoreApiKey);
    console.log("method type: ", req.method)
    if (req.method === 'GET') {
        const query = gql`
        query{
            item(path: "/sitecore/content/MySiteSiteCollection/MySite/Settings" language:"en") {
                field(name: "your field name") {
                    value
            }
          }
        }
      `;

      const data = await graphQLClient.request(query);
      return res.status(200).json(data);
      } else {
        return res.status(400).json({ message: 'Invalid method used.' });
      }
   
};

export default getGlobalItemSettingApi;


This logic will return the response based on the graphql written in this method using http://localhost:3000/api/getglobalitemsetting. 

2. Use that API's response in the Layout.tsx and do your logic what you want to achieve.
Write this code in the 
const Layout = ({ layoutData }: LayoutProps): JSX.Element => {
 const [isMyFieldChecked, setIsMyFIeldChecked] = useState<boolean | null>(null);
  useEffect(() => {
    const fetchChatSetting = async () => {
      try {
        const response = await fetch("/api/getglobalitemsetting");
        if (!response.ok) {
          throw new Error("Failed to fetch global item setting");
        }
        const data = await response.json();
       
        // Extracting the value from the response
        const isValue = data?.item?.field?.value === "1"; // Assuming 1 means enabled
        setIsMyFIeldChecked(isValue);
      } catch (error) {
        console.error("Error fetching chat setting:", error);
      }
    };

    fetchChatSetting();
  }, []);

return (


<div>isMyFieldChecked</div>)

}

Thanks!


get droplink rendering parameter value in xm cloud

You have to set the following configuration to true to get the detailed information on rendering parameters set.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="LayoutService.DetailedRenderingParams" value="false">
        <patch:attribute name="value">true</patch:attribute>
    </setting>
   </settings>
 </sitecore>
</configuration>
By default this setting comes as false.


XM Cloud - Getting component specific data

If you are binding your component with the layout response but feel that if a custom property can come in the layout response and you could bind that in your component.

But as you know you can not insert the custom property in the layout response without heavy customisation but we have a way to do so.

We can achieve this on component level using  useComponentProps and  getStaticProps: GetStaticComponentProps methods in XM cloud.

Lets understand this quickly.

You have a component like follows:

import type {
  ComponentRendering,
  Field,
  GetStaticComponentProps,
  ImageField,
  LayoutServiceData,
  LinkField,
} from '@sitecore-jss/sitecore-jss-nextjs';
import { useComponentProps } from '@sitecore-jss/sitecore-jss-nextjs';
type BlogIndexVariationOneProps = ComponentProps & {
  fields?: BlogIndexVariationOneFields;
};

function BlogIndexVariationOne({
  fields = {},
  rendering = {} as ComponentRendering,
}: BlogIndexVariationOneProps) {

const path = useComponentProps<string>(rendering?.uid);

return (
// your html here
)

}

In the component BlogIndexVariationOne we are passing the BlogIndexVariationOneProps. In this fields will be mapped from the layout response but rendering is worth to pay attention here that we will discuss the usage of it further in this blog.

Now assume that under this component you are returning the HTML with the data received in the fields object and additionaly you have a requirement to show the current page URL in any of the <div> tag also.

So as you know the current url will not work from  window.location.href or writing the same in the useEffect() or even useLocation() won't work until you don't wrap your component in the <Router> tag.

So how can we get the current url then? Here we will use the getStaticProps: GetStaticComponentProps method as shown below:

export const getStaticProps: GetStaticComponentProps = async (

  _rendering: ComponentRendering,
  layoutData: LayoutServiceData,
  context
) => {
  return context?.params?.requestPath
}

Here we are returning the requestPath provided by sitecore's context and it is returning the string type. 

Now how will we use this in our component? Here comes the role of rendering that we passed in the component in the line const path = useComponentProps<string>(rendering?.uid);. So rendering?.uid in the useComponentProps tells the component that something is being passed from getStaticProps: GetStaticComponentProps as string return type so use that.

And voilla, now you can use the request path in your code.

So in place of context?.params?.requestPath you can use your any API fetch if you want it to be fetched using this although the best practice for getting the API data is to use in the useEffect() but this is also one more way to use.

Thanks!

To extend it further with one more example.

In Sitecore JSS / XM Cloud projects (especially with Next.js),
each component can export a getStaticProps method that defines how to fetch its data during build time or static regeneration.

The framework (Sitecore + Next.js) runs this function:

  • once at build time for static generation (next build), or

  • on demand when the page is rebuilt (ISR).

The result of this function gets attached to the component rendering JSON as componentProps — which is what useComponentProps(uid) later reads.


Suppose you have method as follows that get the data using graphql query:

export const getStaticProps: GetStaticComponentProps = async ( _rendering: ComponentRendering, layoutData: LayoutServiceData, context ) => { // Create a GraphQL client to talk to Sitecore XM Cloud const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, { apiKey: config.sitecoreApiKey, }); // Get the current page path (used to construct URLs) const basePath = (layoutData?.sitecore?.context?.itemPath ?? '').replace(/\/,-w-,/, ''); /* page query param handling */ const page = (() => { const path = context?.params?.requestPath; if (path === undefined) return ''; if (!Array.isArray(path)) return ''; const pageNumber = parseInt(path[path.length - 1]); if (isNaN(pageNumber)) return ''; return pageNumber.toString(); })(); /* fetch blog articles */ let updatedResult = []; let query = CHILD_BLOGS_GQL; // Replace placeholders in the GraphQL query with actual IDs query = query.replaceAll('__ROOT_ID__', Constants?.Ids?.BlogItemParent); query = query.replaceAll('__TEMPLATE_ID__', Constants?.TemplateIds?.BlogDetailPage); // Execute the GraphQL query and return all articles updatedResult = await getAllItems<BlogTemplat>(graphQLClient, query); // Return the data that will be serialized into componentProps return { page: page, result: updatedResult, basePath: basePath }; };

and the top somewhere when you would have started your component, there will be code like

const query = useComponentProps<queryResult>(rendering?.uid);
  const data = query?.result;

and,

then do you logic operation based on data variable.

Troubleshoot personalization on xm cloud

Here are the troubleshooting steps below that helped personalization to work. We checked the events analytics in the page builder but it was...