Category: XM Cloud

Setup XM Cloud Site to host on Vercel

In this blog post we will Link the XM Cloud to Vercel. The XM Cloud site will be hosted in Vercel by Seting up the host

In this blog post we saw how to setup the Vercel Project manually but this whole process can be automated by Creating and linking the host.

Configure Hosting Connection

Login to XM Cloud and navigate to Connections –> Hosting tab

Click on Create connection –> Vercel

Login to Vercel and add Integration

Select the account to connect. In my case its personal account

Select the all projects to integrate, dont selecy any specific project or you will get error. See errors section-

Confirm and Add Integration-

A new Hosting connection is created with the name-

Setup Hosting

Navigate to Projects ==> Environments ==> Sites Tab

Link Vercel Site (Connection been already created)

You can create Hosting connection from here too.

Click “Create and link”

Now you can see the Site is linked to host i.e. Vercel.

Once the Site is linked you should be able to see the project in Vercel

Login to vercel and see the newly created project and deployment in-progress.

In few minutes the deployment should be completed

Click on the domains and should see the Site-

Errors-

Vercel installation will require ‘All Projects’ access. Please change the access on the Vercel installation

Resolution

Delete any exisitng Hosting Connection and re-create the hosting with Integration to be allowed to all projects.

Loading

Use Experience Edge GraphQL to access XM Cloud hosted site

GraphQL delivery API is used to access the published site content. Experience Edge for Experience Manager (XM) is an API-based service from Sitecore that gives you globally replicated, scalable access to your XM Cloud items, layout, and media. You can use the standard publish tools in XM Cloud , but instead of rendering content from a self-hosted Content Delivery environment, Experience Edge provides you a Sitecore-hosted GraphQL API. 

To access the XM Cloud hosted published site content using Expereince Edge follow these steps-

Login to XM Cloud. Navigate to Projects ==> Environments ==>Details tab.

Launch IDE for Live GraphQL

The URL for GraphQL IDE –

https://edge.sitecorecloud.io/api/graphql/ide

GraphQL edge endpoint is –

https://edge.sitecorecloud.io/api/graphql/v1

Let stry a simple query to get siteinfo-

If you see this error- JSON.parse: unexpected character at line 1 column 1 of the JSON data

This means a header with GraphQL token is not provided or incorrect.

Generate Delivery API token-

Add X_GQL-TOKEN in header with newly generated token vlaue

You should now be able to access only the published Site content using Experience Edge.

If you are not able to see the items, you might have not published the ietms

Publish items to edge

Loading

Create Vercel project to host XM Cloud Site

Sitecore XM Cloud Vercel connector helps to host Website to Vercel

Before using this connector you have to create Project and Environment.

Prerequisite

Before we ould start configuring Project in Vercel we need following info-

JSS APP Name- can be found and should be same as configured in package.json in sxastarter folder

In this case it is sxastarter

GRAPHQL ENDPOINT

GraphQL endpoint for published Sitecore items i.e. Delivery/Live endpoint is –

https://edge.sitecorecloud.io/api/graphql/v1

Sitecore API Key

This should be the GraphQL Delivery token i.e. GQL token-

There are different ways to generate GQL Token. One of the way is generate from portal. Login to XM Cloud and navigate to Projects ==> Environments ==> Details tab

Click on Generate Delivery API Key (Note this key as this won’t be avilable again and needs to be re-generated again if lost)

Note this API key as this is required later whilst configuring the Vercel hosting.

Publish Site

Publish the site to Edge before starting to configure Project in Vercel, since we are configuring GraphQL Delivery API token items in Sitecore needs to be published

Create a Project in Vercel

Login to Vercel and Create Project-

Since I have logged in using GitHub account it displays the repositories in Github the project will be based on-

Import the repository-

Configure Project

Once the project is created configure the project by selecting the Framework and repo folder FE code exists-

Choose the Nextjs Framework

Choose the sxastarter folder from the repo i.e. /src/sxastarter

Add following environment variables extracted earlier-

JSS_APP_NAME – sxastarter

GRAPH_QL_ENDPOINT – https://edge.sitecorecloud.io/api/graphql/v1

SITECORE_API_KEY – Delivery API Key generated from portal.

Should have this confiogured in the Vercel Project-

Deploy the Project

Deployment complete-

Visit the Site and should get the same view as configued in local environment and Experience Editor-

Thats all for how to create a Vercel Project and deploy site.

Errors-

If you see error-

The field 'item' does not exist on the type 'query'

Resolution-

Publish the site

Loading

Sitecore Headless SXA – Create, apply and restrict a custom style to renderings

In this blog post I will show how to apply a custom style to a rendering.

Requirement-

I have a requirement to add extra spacing between the components.

There is already a indent-top style which provides this space (20px) but neesd 100px space.

And the same can see in Experience Editor-

Same can also see in css file in sxastarter project-

Create a custom style (indent-large-top)

Create custom style in Sitecore-

Create a new style (Indent Large Top) in Sitecore under Presentations => Styles ==> Spacing

/sitecore/content/scxmcloud/sxastarter/Presentation/Styles/Spacing

Provide the value of the Style-

Create a style in FE project with the same value-

There are various ways you should be able to do this. I am adding 5 times more space to the existing indent-top style.

_indent.scss

// $middle-margin is defined in _margins.scss
.indent-large-top {
  margin-top: calc($middle-margin * 5);
}

Apply a custom style to rendering

Select the component or container you want to apply style and choose option “Indent Large Top” in Spacing section

Now the space between the 2 component is increased and is 100px as per the requirement.

New style applied to container-

Apply style to specific renderings

As above when the style was created it was applied to all renderings.

If you want to restrict the style to be applied to only certain renderings you can do so by setting Allowed renderings field in new created Style item.

For “Indent Large Top” only SectionContainer will be able to see the new Spacing Style.

In Experience Editor you wont see the “Indent Large Top” for other renderings e.g.- for container rendering-

While for Section Container rendering the new style is available-

References-

https://doc.sitecore.com/xp/en/developers/sxa/103/sitecore-experience-accelerator/add-a-style-for-a-rendering.html

Loading

How to set background image using Next js in Sitecore XM Cloud

This is a very common scenario where a background image needs to be set to certain components. Banner’s on any page on your website is a very common place to have a background image.

This blog assumes you have setup the Foundation Head setup or have your own Nextjs project setup implemented using the Sitecore NextJS SDK.

Note: This is not specific to XM Cloud but for any Headless implementation

Foundation Head already has an example on setting the background image using params. In this blog post will explore how this works and where in Sitecore the image can be applied. Will see how this can applied using using OOTB _Background Image item.

To apply image background using rendering parameters to the container see this blog here

Applying background image using rendering field to the components

Background image can be applied to components inheriting the existing __Background Image item to the custom component template.

Create a template for your component. Here I am creating a Banner component-

Inherit _Background Image from /sitecore/templates/Foundation/Experience Accelerator/Presentation/_Background Image

_Background Image has “Background Image” and “Stretch mode” field.

Note that there is a space between the field names, although not recommended but this comes OOTB.

Create a “Banner” JSON Rendering and provide the “Parameters Template”, “Datasource Location” and “Datasource Template” as per your requirement and add this rendering to the “Available Renderings”

Create a Nextjs component in sxastarter project

Note below how the “Background Image” field is set. This is due to the same in field name. Not recommended but this is OOTB.

View this gist on GitHub

Experience Editor-

Add a container component in Main placeholder-

Add a newly created component (Banner) in Container placeholder-

Create or select associated content

Once the component is added you should see the button to Add Background Image ( ths is added when the template inherits from _Background Image template.

Select the Background Image and Save-

You should now able to see the background image to component-

Rendering Host-

Reference-

https://doc.sitecore.com/xmc/en/users/xm-cloud/add-a-background-image.html

XM CLoud Dev – How to set background image using rendering parameters

This is a very common scenario where a background image needs to be set to certain components. Banner’s on any page on your website is a very common place to have a background image.

Note: This is not specific to XM Cloud but for any Headless implementation

Foundation Head already has an example on setting the background image using params. In this blog post will explore how this works and where in Sitecore the image can be applied. Will see how this can applied using Rendering Parameters and using OOTB _Background Image item.

Applying background image using rendering parameters

Background image can be applied to container. If you are using Foundation Head repo you can find this component OOTB.

Thre Container rendering is at following lcoation in Sitecore –

/sitecore/layout/Renderings/Feature/JSS Experience Accelerator/Page Structure/Container

Note Other properties- IsRenderingsWithDynamicPlaceholders and IsRenderingsWithDynamicPlaceholders is set to true

Rendering parameter is located – /sitecore/templates/Feature/JSS Experience Accelerator/Page Structure/Rendering Parameters/Container

Rendering paramter template has the BackgroundImage field. The background image will be set based on the image selected in this field.

How the image is set in Head

Lets see background image set in nextjs (sxastarter) Container.tsx

// image string from the rendering parameters
 let backgroundImage = props.params.BackgroundImage as string;
  let backgroundStyle: { [key: string]: string } = {};
  console.log('backgroundImage1');
  console.log(backgroundImage);
  if (backgroundImage) {
    const prefix = `${sitecoreContext.pageState !== 'normal' ? '/sitecore/shell' : ''}/-/media/`;
    backgroundImage = `${backgroundImage?.match(BACKGROUND_REG_EXP)?.pop()?.replace(/-/gi, '')}`;
    backgroundStyle = {
      backgroundImage: `url('${prefix}${backgroundImage}')`,
    };
  }

  return (
    <div className={`component container-default ${styles}`} id={id ? id : undefined}>

// style applied to <div> having background image
      <div className="component-content" style={backgroundStyle}>
        <div className="row">
          <Placeholder name={phKey} rendering={props.rendering} />
        </div>
      </div>
    </div>
  );
};

Lets see this in working in experience editor and rendering host

In the experience editor main section add a container component.

Once the rendering is added, goto “Edit component properties” and add an background image

Now you are able to see the background image applied ot container and I have added RichText in containerto show the image in background-

Rendering Host displays the image in background-

Nested containers to apply differnt background image or component

If you add only one container the image will be applied to the main section.

To resolve this you can add a container within main container. add mutiple containers as per your requirements. To set the background image to specific container in this example contianer-2 select the parent(i.e. container) and set the image by Editing the Component properties

This should apply the different images for various other sections in the sampe page and since the Container rendering has IsRenderingsWithDynamicPlaceholders property set this should create a unique Id for each container.

Here for example container-2 and container-3 is a child of container-1

Rendering Host displays banckgroung images with there respective components-

Isusue- Here you can see there is a white patch when applied to child container and the image is applied to inner div.

To resolev this apply the image to the outer div instead in container.tsx

return (
    <div className={`component container-default ${styles}`} style={backgroundStyle} id={id ? id : undefined}> // backgroundStyle added
      <div className="component-content"> // backgroundStyle removed
        <div className="row">
          <Placeholder name={phKey} rendering={props.rendering} />
        </div>
      </div>
    </div>
  );

Here you can seee a full width background image

Hope these tips helps.

Deploy Headless SXA Site to XM Cloud

In this blog blost lets create Project and Environment to deploy the sxastarter site to XM Cloud. The deployment is based on the existing repository in GitHub and have solution ready to deploy. Please see this blog posts on how to fork Foundation Head Template and setup your local instance along with creating Headless SXA Site(sxastarter) also configure the serliazation of Sitecore items.

To create project and environment you need to have access to XM Cloud either Admin or Contributor.

Login to XM Cloud

https://portal.sitecorecloud.io/

XM Cloud Organization-

Contains organization you are assigned to-

An organization is business unit either company or brand and contains team members and Sitecore Products you are subscribed and can have more than one Sitecore Product as seen in the below screen.

XM Cloud Deploy

As highlighted quick links container XM Cloud Deploy

https://deploy.sitecorecloud.io/

Deploy contanis list of projects and deployments done for each project and environments. It also container connections to GitHub or Vercel if site is hosted their.

The highlighted shows Organization name at the top and list of projects.

Connect to GitHub (Source Control Connections)

Ensure the changes (Sitecore Items) are pushed to GitHub repo.

Recommended – create separate branch for each environment. I have created dev, staging and main(prod)

Connections – should show list of all connections for projects mainly Github and Azure Devop for Source Control, while hosting connections can be mafe to Vercel. In this section we will configure GitHub provider.

Create a new GitHub connection

Should ask to login and provide access to a repository, you may choose all or specific repository-

Since I already had connection you will be shown a different option to Install and Authorize

Create Project

Click on Create project option

This should show the type of project to be created. We want to start from our own Source Code(GitHub) based on the connection made.

Since we configured only GitHub connection defaults to this Source Control-

Your connection name will be displayed here. Choose the connection. This will also show any other connections available.

You may also create a new connection from here.

Provide the project name and the repository where Foundation Head code resides along with any other changes you might have done sa a part of development.

Environment name – provide name – should be able to relate which branch is this pulled from.

Production environment – if this is then choose yes, I have selected this as no since I ma setting dev environment

Linked branch- Select the appropriate branch ensure yuo have all the changes available in this branch which you want to deploy

Trigger deployment on commit to branch – Set if this has to be auto deployed if changes are pushed to selected branch.

Deploy. This should start the deployment. This should take 10 -15 mins. Wait for the post actions.

You should now see the newly created project with dev environment-

New Project Created

New Environment Created

New Site Created (sxastarter)

Select environment and goto Sites tab-

Will see in the next blog hot to setup the Hosting

Select environment and Details tab- You should be able to see hostname, url’s and tokens along with Environment details.

Click on the Dashboard link –> Tools to see if the items are synched-

We now have templates, content and relevant items in layouts and image created

Content Editor with Site Collection, Site and Content

Templates Created

Experience Editor

Lets check the home page in experience editor

In the next bog will configure the Site hosting to Vercel.

Errors-

In connections select Create Connection –> GitHub

Click on Uninstall “Sitecore Deploy Prod”

Follow the process of creating a Connection again and this time you will see option to Install & Authorize

Once this is done an confirmed try creating a project –

Loading

XM Cloud local environment – Configure item serialization to sync Headless SXA instance items

Synchronizing items between environments with Sitecore Serialization. The repository already contains the necessary setup for enabling serialization if you are using an official Sitecore XM Cloud foundation template.

Pre-requisite- Setup Sitecore local instance for XM Cloud development. See this blog << Blog to setup Sitecoer instance>>

You may already see the rendering host module setup in the forked repository.

This should be available in the src folder.

Lets sync the sxastarter site created earlier whilst setting up the SXA Headless Site. << Blog post to setuop SXA headless site>>.

Please note this might not be the method you want to sync the items. Ideally you should create project in XM Cloud and site created in XM Cloud environment. I am doing the other way just to demo.

Create various modules to sync your locally created site to serialize the items

This should help to push the config and items to repository and deploy to XM Cloud later.

Sync templates-

Create a scxmcloud.templates.module.json in src folder.

We are trying to serialise templates to local. These items will be searlised-

{
  "$schema": "../.sitecore/schemas/ModuleFile.schema.json",
  "namespace": "SCXMCloud.Templates",
  "items": {
    "includes": [
      {
        "name": "scxmcloud.project.templates",
        "path": "/sitecore/templates/Project",
        "allowedPushOperations": "CreateUpdateAndDelete"
      }
    ]
  }
}

scope by default is ItemAndDescendants. Hence not defined. Any new templates added here will be auto serialised. allowedPushOperations is set to CreateUpdateAndDelete. Like wise define the same for Feature and Foundation folders.

Define the same for Content (if required) or specific items, Media Library and Layout but this may be site specific.

For media I have configured following – Where scope id Single item and allowedPushOperations is CreateOnly, so these items are created only once.

{
  "$schema": "../.sitecore/schemas/ModuleFile.schema.json",
  "namespace": "SXAStarter.Media",
  "items": {
    "includes": [
      {
        "name": "scxmcloud.project.media",
        "path": "/sitecore/media library/Project/scxmcloud",
        "allowedPushOperations": "CreateOnly",
        "scope": "SingleItem"
      },
      {
        "name": "sxastarter.project.media",
        "path": "/sitecore/media library/Project/scxmcloud/sxastarter",
        "allowedPushOperations": "CreateOnly"
      }
    ]
  }
}

For Palcholder settings and Renderings- Configure same for Feature and Foundation folder.

{
  "$schema": "../.sitecore/schemas/ModuleFile.schema.json",
  "namespace": "SXAStarter.Layout",
  "items": {
    "includes": [
      {
        "name": "sxastarter.project.placeholder",
        "path": "/sitecore/layout/Placeholder Settings/Project/scxmcloud",
        "allowedPushOperations": "CreateUpdateAndDelete"
      },
      {
        "name": "sxastarter.project.renderings",
        "path": "/sitecore/layout/Renderings/Project/scxmcloud",
        "allowedPushOperations": "CreateUpdateAndDelete"
      }
    ]
  }
}

For content- I am searlising the the Site Collection and setting this as CreateOnly with scope defaulting to ItemAndDescendants

{
  "$schema": "../.sitecore/schemas/ModuleFile.schema.json",
  "namespace": "SXAStarter.Content",
  "items": {
    "includes": [
      {
        "name": "sxastarter.content",
        "path": "/sitecore/content/scxmcloud",
        "allowedPushOperations": "CreateOnly"
      }
    ]
  }
}

Finally you should have following modules depending upon the youe site requirements and configuration.

Connect the local environment

After SCS configuration you should connect to local environment. To do so use the following command

This will add the endpoint in user.json file located in .sitecore folder. Alrthough there is a default endpoint which should suffice. Provide your Sitecore instnace host name as appropriate.

dotnet sitecore connect --ref xmcloud --cm https://xmcloudcm.localhost --allow-write true -n local

Local environment should be connected and now can perform sync operations.

An entry will be added in user.json file.

Next pull the items from local Sitecore instance-

dotnet sitecore ser pull -n "local"

If you see this error – ensure the names should be unique. I did a mistake by providing same name in templates module

If you see this error ensure the items to be searialised should be repeated in any other module or any other name. You may also exclude the paths for Feature and Foundation folders – /sitecore/layout/Renderings/Feature/Experience Accelerator

/sitecore/layout/Renderings/Feature/Experience Accelerator

Finally we should have the items seraliased to the items folder-

Items are serliased to support the Home page-

Please note I have synchornised Site Collection, Site and all items of the site.

Managed to have built the home page with some images and texts.

Push these changes to the repo we forked.

Reference-

https://doc.sitecore.com/xp/en/developers/101/developer-tools/sitecore-content-serialization-configuration-reference.html

https://doc.sitecore.com/xmc/en/developers/xm-cloud/walkthrough–setting-up-your-full-stack-xm-cloud-local-development-environment.html

Next will configure Project, environment and deploy the Site to XM Cloud.

Loading

XM Cloud local environment – Access Sitecore database hosted in Docker

This blog provides details on accessing local Sitecore instance Database hosted on Docker.

If you wish to backup or share Sitecore Database you can connect to Sitecore DB.

Install Sitecore local instance, see th blog post here and run the docker containers for Sitecore.

In .env file see the SQL connection details-

Check the docker container for the DB port.

You may also see the Connection String in CM container-

  • Sitecore_ConnectionStrings_Security
  • Sitecore_ConnectionStrings_Core
  • Sitecore_ConnectionStrings_Master
  • Sitecore_ConnectionStrings_Web

From your local installed SQL server connect to docker hosted DB-

You should not able to see the DB’s configured to support Sitecore XM Cloud local instance-

Loading

XM Cloud local environment – Working with GraphQL

Assuming Sitecore local instnace is setup, lets look how to work on Graphql in local machine. See this blog post to setup the local machine for XM Cloud development.

<<Blog post url to setup local instance>>

The GraphQL playground (also called the GraphQL IDE) helps you test GraphQL queries before you use them in your application.

For local instance use the following to open the GraphQL IDE- Assuming local host name is – xmcloudcm.localhost

https://xmcloudcm.localhost/sitecore/api/graph/edge/ide

By default it points to https://xmcloudcm.localhost/api/graph/v1 which is a wrong URL as this URL looks for published items.

Use this URL in your local instance-

https://xmcloudcm.localhost/sitecore/api/graph/edge

This required Sitecore API key and looks for unpublished content which is valid for local instance.

Lets query the site info- Local instance site name is sxastarter

And the API key should be at this location. This api key is required to query using GraphQL

Sample query-

query {
 site {
  siteInfo(site: "sxastarter") {
   name
   rootPath
  }
 }
}

Add headers-

{
  "sc_apikey":"5797FECE-6C74-4535-88AC-5303752CCC99"
}

Results-

You now are ready to use your local machine to query using GraphQL.

Hope this helps.

Loading