Insights

Useful Sitecore Helper Functions for Next.js Sitecore Headless XM Cloud

Enhance your development efficiency with these essential Sitecore helper functions for Next.js Sitecore Headless XM Cloud, complete with descriptions and code samples

Useful Sitecore Helper Functions for Next.js Sitecore Headless XM Cloud

When working with Sitecore XM Cloud and Next.js, having a set of reusable helper functions can significantly improve your development efficiency and maintainability. In this blog, we will explore some useful helper functions, organized within a utils folder in your project structure. We will also provide descriptions and code samples for each function to help you get started.

Creating a utils Folder

To begin, create a utils folder in your Next.js project. This is where we will store all our helper functions, making them easily accessible throughout your application. For more information on structuring a Next.js project in Sitecore XM Cloud, you can refer to this blog.

Helper Functions

Extract UUIDs From a Concatenated String

When dealing with GraphQL queries that return concatenated UUIDs, this helper function can extract them into an array.

Description: This function takes a string of concatenated UUIDs separated by the '|' character and splits it into an array of individual UUIDs.

// utils/extractUUIDs.ts
export function extractUUIDs(concatenatedUUIDs: string): string[] {
  return concatenatedUUIDs?.split('|');
}

Usage:

const uuids = extractUUIDs("DBE28C0C-7CC7-49F0-8881-FBA167FB44E7 | DBE28C0C-7CC7-49F0-8881-FBA167FB44E8 | DBE28C0C-7CC7-49F0-8881-FBA167FB44E9");
console.log(uuids); // ["DBE28C0C-7CC7-49F0-8881-FBA167FB44E7", " DBE28C0C-7CC7-49F0-8881-FBA167FB44E8", " DBE28C0C-7CC7-49F0-8881-FBA167FB44E9"]

Convert Sitecore Date

Sitecore dates are often in a specific format that needs to be converted for use in JavaScript.

Description: This function converts Sitecore date strings to JavaScript Date objects.

// utils/convertSitecoreDate.ts
export default function convertSitecoreDate(sitecoreDateString: string) {
  if (!sitecoreDateString) {
    return null;
  }
  const formattedString = sitecoreDateString.replace(
    /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})$/,
    '$1-$2-$3T$4:$5:$6'
  );
  const date = new Date(formattedString);
  if (isNaN(date.getTime())) {
    return null;
  }
  return date;
}

Usage:

const sitecoreDateString = "20230612T120000";
const date = convertSitecoreDate(sitecoreDateString);
console.log(date); // Mon Jun 12 2023 12:00:00 GMT...

Replace Domain in URL

When migrating content or changing domains, you might need to replace domains in URLs.

Description: This function replaces the domain part of a URL with a new domain.

// utils/replaceDomain.ts
export function replaceDomain(url: string): string {
  const newDomain = 'example.com';
  const regex = /^(https?:\/\/)?(www\.)?[^\/]+/;

  url = url.replace(regex, (match, prefix, www) => {
    const httpPrefix = prefix ? prefix.replace('http://', 'https://') : 'https://';
    const wwwPrefix = www ? www : 'www.';

    return `${httpPrefix}${wwwPrefix}${newDomain}`;
  });

  return url;
}

Usage:

const oldUrl = "http://example.com/page";
const newUrl = replaceDomain(oldUrl);
console.log(newUrl); // https://www.cpacanada.ca/page

Description: To avoid repeatedly checking if a link field has an href value, use this helper function. It simplifies the process by returning a boolean.

// utils/isLinkSet.ts
export const isLinkSet = (linkField: LinkField) => {
  return !!linkField?.value?.href;
};

Usage:

import { isLinkSet } from './utils/isLinkSet';

{isLinkSet(productLink) && (
  <NextLink href={productLink.value.href} target="_blank">
      <span className="button-text">Button Title</span>
    )}
  </NextLink>
)}

Get Query Parameter Value

Sometimes, you need to extract query parameters from a URL.

Description: This function retrieves the value of a specified query parameter from a URL.

// utils/getQueryParam.ts
export function getQueryParam(url: string, param: string): string | null {
  const urlParams = new URLSearchParams(new URL(url).search);
  return urlParams.get(param);
}

Usage:

const url = "http://example.com/page?param1=value1&param2=value2";
const paramValue = getQueryParam(url, 'param1');
console.log(paramValue); // "value1"

Final Words on Useful Sitecore Helper Functions

Having a utils folder with reusable helper functions can greatly enhance your productivity and code quality when working with Sitecore XM Cloud and Next.js. These functions provide solutions for common tasks and can be easily extended or modified to fit your specific needs. Feel free to implement these examples and share your experiences or additional helper functions that you find useful. We will continue to introduce new helper functions in future blogs.



Meet Sohrab Saboori

Senior Full-Stack Developer

💪👨‍💻🤼

Sohrab is a Senior Front-End Developer with extensive experience in React, Next.js, JavaScript, and TypeScript. Sohrab is committed to delivering outstanding digital solutions that not only meet but exceed clients' expectations. His expertise in building scalable and efficient web applications, responsive websites, and e-commerce platforms is unparalleled. Sohrab has a keen eye for detail and a passion for creating seamless user experiences. He is a problem-solver at heart and enjoys working with clients to find innovative solutions to their digital needs. When he's not coding, you can find him lifting weights at the gym, pounding the pavement on the run, exploring the great outdoors, or trying new restaurants and cuisines. Sohrab believes in a healthy and balanced lifestyle and finds that these activities help fuel his creativity and problem-solving skills.

Connect with Sohrab