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.';
<span class="hljs-keyword">return</span> <span class="hljs-string"><span class="hljs-string">`</span><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst">${httpPrefix}</span></span></span></span></span><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst">${wwwPrefix}</span></span></span></span></span><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst"><span class="hljs-string"><span class="hljs-subst">${newDomain}</span></span></span></span></span><span class="hljs-string">`</span></span>;
});
return url;
}
Usage:
const oldUrl = "http://example.com/page";
const newUrl = replaceDomain(oldUrl);
console.log(newUrl); // https://www.cpacanada.ca/page
Check if Link Has href
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¶m2=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.