Configuring GraphQL and Running your first query in XM Cloud NextJs App using ContentSDK

While working on real-world Sitecore projects, there are many scenarios where you need to fetch global content values that are reused across the entire site. Although we can retrieve item field values from data source items inside components in Next.js, there are times when we need to fetch content directly from the Sitecore CMS rather than through a component’s data source.

One of the most recommended approaches for this requirement is to execute GraphQL queries which use the Sitecore Edge API under the hood and return data in a strongly-typed schema.

In this blog, I will explain how to configure and execute GraphQL queries in a Next.js application using the Sitecore Content SDK.

About Sitecore ContentSDK

Sitecore XM Cloud brings a headless, API-first approach to content delivery. While GraphQL queries can be executed directly through Edge endpoints, Sitecore has introduced the Sitecore Content SDK to make this development experience even easier.

The Sitecore Content SDK is a lightweight and modern toolkit that makes it easier for developers to consume content from Sitecore XM Cloud / SitecoreAI. Instead of manually handling API calls, tokens, and GraphQL endpoints, the SDK provides a simple and unified way to fetch pages, components, dictionary phrases, and media directly into your front-end application. With native support for frameworks like Next.js, it enables faster development, cleaner code, and seamless integration with visual editing and personalization features in Sitecore.

Implementation

For this blog, i will create a simple item from a template and will read the value by running the graphql query.

Given a scenario, suppose you want to redirect to some url if session goes timeout. But the url should come from CMS. I will show you how you can retreive that url using graphql query.

Step 1: Create data item



To run my query, i just need the item path and field name property as of now. Please note, i am trying to fetch /about value from TimeoutRedirectUrl field. Field type is droptree


Step 2: Create Sitecore Client using Content SDK



import { SitecoreClient } from '@sitecore-content-sdk/nextjs/client';
import scConfig from 'sitecore.config';

const client = new SitecoreClient({
  ...scConfig,
});

export default client;

Explaining a bit about it:
  • SitecoreClient is the main object provided by Sitecore Content SDK. 
  • scConfig usually contains the settings required to connect to Sitecore XM Cloud / Edge. This uses graphql end point and api key which you provide in .env.local file
  • The ...scConfig spreads all the properties inside the object.
  • Now client knows how to call GraphQL content queries, Layout service, Search, Media asset requests etc.
  • Returning the client.
Step 3: Executing the graphql in GUI

For this, you need to know your GraphQL IDE link. You can get it from Sitecore XM Cloud deploy app, Once you reach here, click on Launch IDE.

Step 4: Build and Running the query 



Please note we wanted to grab url value i.e /about

Step 5: Running same query in NextJs App


Code:

"use client";
import { useEffect } from "react";
import client from "../lib/sitecore-client";

interface SettingsResponse {
  item: {
    SessionTimeoutUrl: {
      value: {
        url: string;
      };
    };
  };
}

const settingQuery = `
query GetItemByPath {  item(
    path: "/sitecore/content/FRB/DirectAxis/corporate-website/Data/Journey/Journey Global Settings"
    language: "en"
  ) {
    SessionTimeoutUrl: field(name: "TimeoutRedirectUrl") {
      value: jsonValue
    }
  }
}
`;

export default function GlobalFormLoadEventListenerProvider({ children }: { children: React.ReactNode }) {
  console.log("Entered GlobalFormLoadEventListenerProvider");
  useEffect(() => {
    const  data = client.getData<SettingsResponse>(settingQuery).then((data: SettingsResponse) => {
      const timeoutRedirectField = data?.item?.SessionTimeoutUrl?.value?.url;
       console.log("timeoutRedirectFieldvalue:", timeoutRedirectField);
    });
  }, []);
  return <>{children} </>;
}

Please note: Since we are using the droptree field type, You should be able to get the url value from it

const timeoutRedirectField = data?.item?.SessionTimeoutUrl?.value?.url;


Step 6: Output


Conclusion

In this blog, I have shown how you can fetch the field value from a data item using GraphQL query using Sitecore Content SDK. Similarly, you can fetch whole set of fields from a given item which can be utilise in whole application

References

https://doc.sitecore.com/sai/en/developers/content-sdk/sitecore-content-sdk-for-sitecoreai.html


Comments

Popular posts from this blog

Working with Device Detection Module in Sitecore

Setup A/B Testing in Sitecore - Part 1

Resolving: Failed to start service Sitecore Marketing Automation Engine Error