Category: Headless Development

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

XM Cloud local environment – Setup a separate JSS application for Headless SXA site

In this blog post we wil setup nextjs application i.e. sxastarter assuming your local Sitecore instance is up and running.

We will create a Headless SXA site in Sitecore local instance and then setup the FE application. This is can also moved outside the Foundation Head repo so that FE devs can work on this spearately.

Setup JSS app to work with local Sitecore instance

Ensure you have Sitecore instance up and running see this blog << 2. XM CLoud for local env>> or you can also see this blog

1. Setup your JSS app

Ensure you execute this commands on FE folder i.e. /src/sxastarter

Ensure you have Sitecore JSS CLI installed on local machine

 

Once this is installed Setup the JSS app-

jss setup

Following is required to setup-

jss setup
Is your Sitecore instance on this machine or accessible via network share? [y/n]: n

Sitecore hostname (e.g. http://myapp.local.siteco.re; see /sitecore/config; ensure added to hosts): https://xmcloudcm.localhost
Sitecore import service URL [https://xmcloudcm.localhost/sitecore/api/jss/import]:
Sitecore API Key (ID of API key item): {5797FECE-6C74-4535-88AC-5303752CCC99}
Please enter your deployment secret (32+ random chars; or press enter to generate one): 

Provide the Sitecore hostname and the api secret, in this case xmcloudpreview item id at following location /sitecore/system/Settings/Services/API Keys/xmcloudpreview

Note the deployment secret. This is required to setup Headless Site, in this case it is bz39czqkd47o0n7nvfm11kaoexuouk5dq2z4fhsrl3

Also note the sscjssconfig.json file updated.

2 . Create a Healdess Tenant and Site

In your Sitecore instance create a Healdess Site Collection, you may create a folder Site Collection Folder if required-

Next provide the Site collection name, in this case scxmcloud and select the required modules-

You should see the Site collection created along with the required templates in Project/scxmcloud folder.

Setup should create folders and required items in following location. Note this as this is required whilst setting the item sync using Sitecore SCS (Sitecore Content Serialization)

Layout Placeholder Settings- /sitecore/layout/Placeholder Settings/Project/scxmcloud

Layout Renderings – /sitecore/layout/Renderings/Project/scxmcloud

Media Library – /sitecore/media library/Project/scxmcloud

Templates – /sitecore/templates/Project/scxmcloud

Create a Headless SXA Site

Create headless site under site collection-

Provide the name of the site- sxastarter

Select the modules- Note I selected the basic site module. This should add sample items to home page along with About page. You may choose not to select the basic site module.

Enter the deployment secret created whilst setting up the JSS app

Site should now be created-

Site without Basic Site module-

Open the experience editor and you should see the blank page-

Lets add the Title component to see if the changes are reflecting in Experience Editor and FE.

Testing GraphQL IDE for local environment

Try the graphql ide here on your local instance –

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

And the request for same should be sent to –

https://xmcloudcm.localhost/api/graphql/v1

We now have site ready to start developing components.

Run the FE site

On your root folder /src/sxastarter folder run following-

npm install
npm run start:connected

npm install – should download all the required dependencies

You may fix any vulnerabilities by running-

npm audit fix
OR
npm audit fix --force

Before starting the jss app ensure the app name in Sitecore matches the app name in package.json file.

If you wish to change the app name you to make changes in Sitecore and package.json file.

To start the sxastarter jss app run-

npm run start:connected

If no errors the app should be available on http://localhost:3000

The newly added title in header should also be displayed-

Managed to add inbuilt components to page-

This conculdes setting up the local environment with having Sitecore CM instance and the jss app (FE) running on localhost. Note JSS app is not runing on containers as we should not force FE devs to work on containers. This scenario is good for Sitecore developers for bulding and testing the components locally.

You may pull out the sxastarter folder outside this repo and FE devs should be good to develop on theri own. Although there is a dependency to have Sitecore instance hosted on local environment.

In next blog post we will how to setup the FE without having Sitecore local instance and connect to XM Cloud.

But before that we need to setup the XM Cloud project and environments, for that we will configure the Sietcore Content Serilization to push the changes made in local to XM Cloud. Coming in next blog.

Connect your local FE app to XM Cloud.

Although not recommended but if you want ot connect the XM Cloud instance to local FE app. Follow these steps.

I need to make changes in 2 places to get this working.

docker-compose.override.ymlrendering

Change environement settings–

SITECORE_API_HOST – The host name of XM instance.

SITECORE_API_KEY- This is the delivery api token

Generate this from XM Cloud if not done before.

    environment:
      SITECORE_API_HOST: "https://your-instance.sitecorecloud.io" #"http://cm""http://${CM_HOST}"
      NEXTJS_DIST_DIR: ".next-container"
      PUBLIC_URL: "https://${RENDERING_HOST}"
      JSS_EDITING_SECRET: ${JSS_EDITING_SECRET}
      SITECORE_API_KEY: "your_delivery_api_token" #"${SITECORE_API_KEY_xmcloudpreview}"
      DISABLE_SSG_FETCH: ${DISABLE_SSG_FETCH}
      NODE_TLS_REJECT_UNAUTHORIZED: 0

FE (sxastarter) .env file-

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

Spin-up the containers again and shold render the content

Hope this helps.

Loading

XM Cloud local environment – Setup a JSS application – sxastarter for Headless SXA site

In this blog we will create a Headless SXA Site in local instance, setup and resolve any errors while running the rendering app (sxastarter)

We will create a Headless SXA site in Sitecore local instance and then setup the FE application.

With the local Sitecore instance(CM) you should also see the rendering host is configured i.e. https://www.sxastarter.localhost/

While seting up the local instance we haven’t made any changes to docker compose or override files nor to the .env files manually, although while initalizing the app certian key values were updated in .env file.

Check the sxastarter rendering host- https://www.sxastarter.localhost/

At this point you might see the error since we haven;t created a sxastarter app in Sitecore.

This is because the no Site Collection or Headless Site exists in Sitecore. Lets create a Headless Tenant and Site.

2 . Create a Healdess Tenant and Site

In your Sitecore instance create a Healdess Site Collection, you may create a folder Site Collection Folder if required-

Next provide the Site collection name, in this case scxmcloud and select the required modules-

You should see the Site collection created along with the required templates in Project/scxmcloud folder.

Setup should create folders and required items in following location. Note this as this is required whilst setting the item sync using Sitecore SCS (Sitecore Content Serialization)

Layout Placeholder Settings- /sitecore/layout/Placeholder Settings/Project/scxmcloud

Layout Renderings – /sitecore/layout/Renderings/Project/scxmcloud

Media Library – /sitecore/media library/Project/scxmcloud

Templates – /sitecore/templates/Project/scxmcloud

Create a Headless SXA Site

Create headless site under site collection-

Provide the name of the site- sxastarter.

You may choose another name but ensure the package.json file is updated accordingly.

Select the modules- Note I selected the basic site module. This should add sample items to home page along with About page. You may choose not to select the basic site module.

Enter the deployment secret created whilst setting up the JSS app

Site should now be created-

Site without Basic Site module-

Keep the Site Settings as is-

sxastarter site is created along with this the choosen mdoules are installed.

Once this is done ensure the app name in Settings is same as in package.config-

Open the experience editor and you should see the blank page-

Lets add the Title component and images to see if the changes are reflecting in Experience Editor and FE.

Visit the https://www.sxastarter.localhost/ and the images are not loading

This is due to the local instance has relative media url for local instance.

Solution-

Patch the local instance to include – IncludeServerUrlInMediaUrls

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:env="http://www.sitecore.net/xmlconfig/env/">
  <sitecore>
    <layoutService env:require="Development">
      <configurations>
        <config name="sxa-jss">
          <rendering>
            <renderingContentsResolver>
              <IncludeServerUrlInMediaUrls>false</IncludeServerUrlInMediaUrls>
            </renderingContentsResolver>
          </rendering>
        </config>
      </configurations>
    </layoutService>
  </sitecore>
</configuration>

I did this in VS, Platform project. Added the config file in App_Config/Include/Feature named z.Plaform.Feature.IncludeServerUrlInMediaUrls.config

Publish the project and this file should be then deployed to CM container.

Now this should display the images-

Testing GraphQL IDE for local environment

Try the graphql ide here on your local instance –

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

And the request for same should be sent to –

https://xmcloudcm.localhost/api/graphql/v1

We now have site ready to start developing components.

The newly added title in header, images should also be displayed-

This conculdes setting up the local environment with having Sitecore CM instance and the jss app (FE) running in docker. JSS app is runing in container.

In next blog post we will how to setup the FE without having Sitecore local instance and connect to XM Cloud.

But before that we need to setup the XM Cloud project and environments, for that we will configure the Sietcore Content Serilization to push the changes made in local to XM Cloud. Coming in next blog.

Errors-

sxastarter site hosted in docker throws below error.

Solution

See the resolution for this error here

https://sitecore.stackexchange.com/questions/35307/sitecore-xm-cloud-local-setup-error-with-node-js

I updated the rendering Dockerfile –> Entrypoint to clean and install the npm

npm ci && npm run start:connected

This should resolve the issue. Hope this helps.

Loading

XM Cloud local environment – Setup local development instance

This blog post will guide you through the local environment setup for XM Cloud. You may refer this documentation to do this your own way. Althoug the documentation covers most of the setup, this blog post provides visual on the steps and errors with the resolution.

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

Once the Foundation Head from Sitecore Labs is forked s(se more details here) clone the copy to the local machine for creating a local instance required for XM Cloud development.

Pre-requisite

You can find the pre-requisite in this documentation. Ensure your machine has this before setting the local development environment. Just noting down here-

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

Also make sure you are using Docker v.2, as explained here.

Access to XM Cloud – This blog post assumes you have admin access to XM Cloud where you should be able to craete/update/delete projects environments and deployment in your organisation.

I have this ready on my machine.

1. Clone the forked Foundation head repo.

I named the folder same as the repo on my local machine i.e. xmcloud-foundation-head. the same will be refered thoruhg this post.

Will see the following folder structure after cloned.

I use Visual Studio Code to make any environment related changes. You may use either Visual Studio 2022 or your choice of editor.

2. Open the .env at the root folder and you will see REPORTING_API_KEY, TELERIK_ENCRYPTION_KEY etc. empty.

3. Start the containers.

Prepare the environment

Before doing so make sure you stop the IIS and check if the port 443 (IIS Website) and 8984 (Solr service)is not used and the docker is running in Windows Containers mode. If not switch to Windows cotainers.

iisreset /stop
Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess
Get-Process -Id (Get-NetTCPConnection -LocalPort 8984).OwningProcess

Stop-Service -Name "<the name of your service>"

Copy the license file to c:\license folder. If you wish to have this in other folder you also have to change the HOST_LICENSE_FOLDER in .env(root folder) with the path where the license resides.

To prepare the Sitecore container environment, run the script init.ps1 from the root directory of the project along with the license path and desired passowrd for your instance. this form the root folder from the downloaded the repo.

.\init.ps1 -InitEnv -LicenseXmlPath "C:\license\license.xml" -AdminPassword "b"

Required certificates added.

You may also noticed .env in root folder have added values in REPORTING_API_KEY, TELERIK_ENCRYPTION_KEY and MEDIA_REQUEST_PROTECTION_SHARED_SECRET, which was earlier empty.

Download the Sitecore Docker images, install and configure the containers and client application

Run the up.ps1 to download and install containers and client application

.\up.ps1

This is should download the images and start the containers

Once the containers are started, it should ask to confirm to login to Sitecore with the Device confirmation code. Confirm if this matches. It should also ask to login to XM Cloud isntance and confirm.

One this is done indexes will be rebuilt and the Sitecore instance should be up and running.

Also notice that any items in this case none is pushed to Sitecore instance and an api key is genereated with the name xmcloudpreview-

You may also notice a jss editing secret and SITECORE_API_KEY_xmcloudpreview are updated in .env fiel in root folder along with the Sitecore Admin password which was set whilst initialising the environment.

Your local instance should now be up and running-

https://xmcloudcm.localhost/sitecore/

The highlighted key shoulld match the key while spinning up the containers.

Taking down the containers

To take down the containers run the down.ps1 from the root folder.

.\down.ps1

Errors

Invoke-RestMethod : Unable to connect to the remote server

This should be ideally staright forward but if you see any issues whilst getting CM instance up and runing. take down the container with down.ps1 command and delete any docker network.

docker network prune

Hope this helps to setup local Sitecore instance for XM Cloud development.

Loading

Debug, inspect, test and run the request triggered by XM Cloud Webhook using ngrok

Sitecore Webhooks allows to receive real-time notification about events to the web api that can handle these requests.

In this blog post will see how to debug such handlers in local environment, events triggered by XM Cloud or from the local instance using ngrok.

What is ngrok?

ngrok allows to connect external netwroks in a consistent, secure and repeatable manner without changing any network configurations.

Pre-requisite-

Sitecore Instance-

Either have a local Sitecore instance or XM Cloud instance. See how to setup local XM Cloud instance

Create a Webhook Handler(Web Api)

For this blog post I have created a simple Web Api with a endpoint /api/item/handler which receives POST requests with a Item payload and just return OK or Badrequest response.

We are going to create a Webhook with item:saved event in Sitecore.

using Microsoft.AspNetCore.Mvc;
using Sitecore.Webhook.Handler.Models;

namespace Sitecore.Webhook.Handler.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ItemController : Controller
{
    [HttpPost("handler")]
    public async Task<IActionResult> ItemHandler(ItemPayload? payLoad, 
        CancellationToken cancellationToken)
    {
        if (payLoad == null)
        {
            return BadRequest();
        }

        // Process the item handler
        return Ok();
    }
}

When I run this from VS the endpoint listens on the port 7024 for me.

Host Name:- https://localhost:7024/

Endpoint: /api/item/handler

Install ngrok on dev machine

Use choclatey to install ngrok on local machine

choco install ngrok

Check the ngrok once installed

ngrok -v

IMP– Antivirus might block executing the ngrok. For me I had to turn off the real time scan. Do this at your own risk based on your antivirus software this might be different.

Execute ngrok http command to listen to the api endpoint-

ngrok http --host-header="localhost:7024" https://localhost:7024

In this example https://1a319cf7d867.ngrok.app should forward request’s to https://localhost:7024 where the Web Api is running on my local machine.

Also note the Web Interface – http://127.0.0.1:4040/

Create a Webhook Handler

Navigate to /sitecore/system/Webhooks and create a webhook handler. In this case will create a item:saved handler.

In the newly created handler select the event the webhook should trigger and call the endpoint created by nrgok (i.e. web api)

Setup the rule – “where the item is the Home item or onle of its descendants”

Means Home or any of its child items when saved this event will be triggered.

Also setup the Url the webhook should call when this event fires.

IMP – Ensure the handler is enabled or it won’t fire the event.

Save the Home or any of its child to fire the event

I changed a field in Home item and Saved the item-

Ensure your Web Api solution is running in debug mode.

And now you should be able to debug, inspect and test the handler. This was done in local Sitecore instance but can also be done in XM Cloud.

ngrok helps to forward the requests to the localy hosted web api running in debug mode.

Now you can handle what should happen on item:saved event.

XM Cloud

I did the same process in XM Cloud-

Updated the Home item and Saved. Note the item id

The event is fired and web api in my local machine is called-

Also the ngrok also shows the calls it is listening.

Web interface should also show the request and payload details-

Hope this helps debuging your Webhook requests fired from Sitecore local or XM Cloud.

If you want to see the webhook payload and perform further actions, like sending mails etc there are online tools availabl e-

https://webhook.site/

https://zapier.com/

https://hookdeck.com/

https://ifttt.com/

Hope this helps.

Loading

Setting up a Sitecore JSS development environment with the Containers template for Next.js

Follow steps in this link —

https://doc.sitecore.com/xp/en/developers/hd/211/sitecore-headless-development/walkthrough–setting-up-a-development-environment-with-the-sitecore-containers-template-for-next-js.html

Following are thre pre-requisite for setting on your local machine-

Apart from this also install Sitecore JSS CLI-

npm install -g @sitecore-jss/sitecore-jss-cli

Install the template

dotnet new -i Sitecore.DevEx.Templates --nuget-source https://sitecore.myget.org/F/sc-packages/api/v3/index.json

dotnet new sitecore.nextjs.gettingstarted -n samplejss

Should first Restores dotnet local tools for the solution and Initializes the JSS project

What is your Sitecore hostname (used if deployed to Sitecore)? (samplejss.dev.local) << leave blank or provide the host name>>

How would you like to fetch Layout and Dictionary data? 
GraphQL
REST

How would you like to prerender your application?
SSG
SSR

Which additional language do you want to support (en is already included and required)? << leave blank or type the language you want. should select da-DK by default and additional language>>

JSS application is now ready and updated for continerized environment.

Navigate to project folder and initialize the environment.

.\init.ps1 -InitEnv -LicenseXmlPath "<C:\path\to\license.xml>" -AdminPassword "<desired password>"
setx NODE_EXTRA_CA_CERTS C:\Users\sandeep\AppData\Local\mkcert\rootCA.pem

Execute up.ps1 to create containers-

.\up.ps1

Error-

CM is not coming up-

Checked the docker logs, and found this error-

The path is not set correctly. Need to escape the characters-

Resolution-

Change – entrypoint: powershell.exe -Command “& C:\tools\entrypoints\iis\Development.ps1” to entrypoint: powershell.exe -Command “& C:\\tools\\entrypoints\\iis\\Development.ps1” in docker-compose.override.yml file for xm1, xp0 and xp1

Take down all the containers and build again.

Now this should look fine-

Enter CM admin credentials and allow the access-

CM and App should load –

As of writing this post, this setup installed Sitecore 10.3.

Loading

Setup Sitecore Headless SXA with Next js

Pre-requisite-

Install Sitecore 10.3 XP0 on local machine – see this blog to install the SIF way

Install Powersehll Extensions

Sitecore PowerShell Extension for Sitecore on your local Sitecore instance

Sitecore Headless Rendering 21.0.0

Install Sitecore Headless Services for Sitecore XP on your local Sitecore instance

See the Sitecore Headless Rendering 21.0.0 download page

Install SXA module –

Sitecore Experience Accelerator on your local Sitecore instance

See the Sitecore Experience Accelerator 10.3.0 dowload page

Once you have the above installed the local instance should have options to create a Headless Tenant and Folder

Ensure all the search index and rebuilt-

Install Node js Download | Node.js (nodejs.org). Latest whilst writing this blog was v18.14.0

Create a Headless Tenant

Select the Headless Tenant

Enter a valid tenant Name and the modules to install –

Should create a tenant successfully-

Create a Headless Site

Now create a Headless Site

Provide a valid Site name and other options-

Select the modules to install-

Keep the Site settings as is for now and will generate the deployment secret later-

Site should be crated within the tenant-

Setup the rendering host

Site Settings – Check for the rendering host- should have set to Default

/sitecore/content/mycompany/retail/Settings/Site Grouping/retail

Find the Default rendering host on this location-

/sitecore/system/Settings/Services/Rendering Hosts/Default

Server side rendering engine endpoint URL:- http://localhost:3000/api/editing/render

Server side rendering engine application URL:- http://localhost:3000

Application name:- e.g.:- retail-app

Where is the above value coming from – when a next js app is created by default it is hosted on port 3000. Please see section below- NEXT STEPS

Create JSS Api key

Navigate to this location to create API key- /sitecore/system/Settings/Services/API Keys

Provide a valid name-

Set the CORS and Allowed Controllers to all domains. Set this to *

Will need API key while setting up the next js app.

Install JSS globally

https://doc.sitecore.com/xp/en/developers/hd/200/sitecore-headless-development/install-the-jss-cli-globally.html

npm install -g @sitecore-jss/sitecore-jss-cli

Initialise JSS App

Refer following for various options –https://doc.sitecore.com/xp/en/developers/hd/210/sitecore-headless-development/the-jss-app-initializer.html

Use following command-

npx create-sitecore-jss --templates nextjs,nextjs-sxa --appName retail-app --hostName xp103.sc --fetchWith GraphQL

Possible values for templates arguments-

Base templatesnextjs. Other possible values-

Other templates

appName – enter the app name provided in the rendering host. See Setup the rendering host section

hostname– enter the hostname of the Sitecore instance

While installing following questions are asked-

? Where would you like your new app created? – provide the location to create a next jss app

? How would you like to prerender your application? – Select SSG

Understand the pre-rendering to select. In this case I have selected SSG option.

https://doc.sitecore.com/xp/en/developers/hd/190/sitecore-headless-development/prerendering-methods-and-data-fetching-strategies-in-jss-next-js-apps.html

https://doc.sitecore.com/xp/en/developers/hd/210/sitecore-headless-development/switch-the-pre-rendering-method-in-a-jss-next-js-app.html

Following files will be created in a new folder (retail-app) –

Setup JSS app-

see this link- https://doc.sitecore.com/xp/en/developers/hd/190/sitecore-headless-development/start-a-jss-app-in-disconnected-mode.html

Setup the JSS app-

jss setup

Following options are asked, provide the required details-

Is your Sitecore instance on this machine or accessible via network share? [y/n]: y

Path to the Sitecore folder (e.g. c:\inetpub\wwwroot\my.siteco.re): C:\inetpub\wwwroot\XP103.sc

Sitecore hostname (e.g. http://myapp.local.siteco.re; see /sitecore/config; ensure added to hosts): https://xp103.sc

Sitecore import service URL [https://xp103.sc/sitecore/api/jss/import]: [Leave blank]

Sitecore API Key (ID of API key item): B418AB1D-A7A9-48F4-9A96-51F7D6C2105F [enter the api key created earlier- see section Create JSS Api key ]

Please enter your deployment secret (32+ random chars; or press enter to generate one): [Leave this blank and it should create one or enter the value here]

See the highlighted values. Also note the where the deployment secret is written-C:\projects\Sitecore\HeadlessSXA\retail-app\sitecore\config\retail-app.deploysecret.config

NEXT STEPS

Remove/Comment the site definition in this case as opposed to JSS sites as this will be handled in Sitecore site settings-

Remove it from /sitecore/config/retail-app.config

Verify JSS app registration-

See the values of Endpoint Url and Application URL. The same url was configured in rendering host.

Set JSS Editing Secret in .env file- Use the deployment secret from the /sitecore/config/app-name.deploysecret.config

Deploy config

jss deploy config

Note the config was deployed to C:\inetpub\wwwroot\XP103.sc\App_Config\Include\zzz folder in the Sitecore instance

Start Application in connected mode

jss start:connected

Application should listen to http://localhost:3000

Try accessing – http://localhost:3000

Errors:-

Solution

$env:NODE_TLS_REJECT_UNAUTHORIZED=0

Error-

Solution-

Search for root item in code- open \src\lib\dictionary-service-factory.ts

Error- Page not found

Solution – Ensute the site and the app name is same.

After all the above errors, it should show the blank page- Since there are no component s added.

Lets add some content, for this opne the Home page in experienec editor and see this error-

Error- Connection to your rendering host failed with an Unauthorized error. Ensure the JSS Editing Secret is configured.

Update the JSS Editing Secret in Sitecore instance at following path (best practice-you have to patch the config instead of updating the Sitecore configs directly)

App_Config\Sitecore\JavaScriptServices\Sitecore.JavaScriptServices.ViewEngine.Http.config

Update the value to the deployment secret used earlier in .env file-

After update-

Finally we can see the experience editor-

Add some content –

Save and Publish

Finally we have next js app showing the content- on localhost:3000

Layout Services

Lets check if the layout services are accessible-

Get Item data (home) and secret key-

https://xp103.sc/sitecore/api/layout/render/jss?item={40A111E6-6B4D-41D5-BA0D-FD993C5D00E4}&sc_apikey={B418AB1D-A7A9-48F4-9A96-51F7D6C2105F}

Graphql

https://xp103.sc/sitecore/api/graph/edge/ui?sc_apikey={B418AB1D-A7A9-48F4-9A96-51F7D6C2105F}

Loading