Get started with XM Cloud + Next.js locally + deploy to Vercel in a matter of minutes

Last week the Sitecore Symposium took place in Chicago after 3 years without having the in-person event, it was amazing to be back there and meet with people in person as well as the amazing community folks during the MVP summit.

One of the main announcements was the release of XM Cloud to the public, even though we already knew about the product, and had been able to test and play with it for a while now so decided to write a quick step-by-step guide to help devs getting started, get a better understanding on the development workflow, have a quick overview of the product and so on so forth.

For this demo, I’m not spinning up any local environment (Docker containers), to make it really simple, assuming we want only to tackle it from the front-end side development and we’re not deploying any customization to the XM.

About XM Cloud

Sitecore Experience Manager Cloud (XM Cloud) is a fully managed self-service deployment platform for developers and marketers to efficiently launch engaging omnichannel experiences in the Cloud using Sitecore’s headless CMS. Experience Manager Cloud bundles the latest versions of Experience Manager, the Pages editor, Sitecore Headless Experience Accelerator (SXA), Headless Services, the Sitecore Next.js SDK (and other Heads), and Experience Edge.

With an optimized cloud-based strategy, you can rapidly and cost-effectively scale to meet your customers’ needs, shorten your time-to-market, and be more adaptive as new capabilities and functionality are added to your Martech stack. Explore how the right cloud approach will help you thrive now and into the future.

Sitecore Experience Manager Cloud re-imagines Content Management and introduces a no-compromise Content Management System (CMS) that delivers developer agility through the best attributes of the headless CMS while empowering marketers through a visually rich, WYSIWYG page composition experience. With XM Cloud, our customers can deliver relevant experiences at high speed.

  • Speed: Visitors are greeted with an experience that loads lightning-fast and engages instantly
  • Relevance: Customers are recognized and welcomed back to an experience that understands their needs

The importance of your company’s growth comes with the:

  • Agility: Marketers can easily orchestrate the overall experience across digital campaigns
  • Flexibility: Developers can rapidly develop and launch new experience types with modern front-end frameworks

XM Cloud

Architecture

XM-Cloud Architectire

XM Cloud comes with a Content Management application based on Sitecore XM including known but also new editing Tools. So, you will be able to use Content Editor as well as Experience Editor. In addition to these powerful tools, XM Cloud includes Sitecore Pages to manage your content and Design Pages, and many other tools.

The content delivery is provided by publishing to Edge. That can be Sitecore Edge (configured as default) but also other edge vendors.

Edge delivers content and design information headlessly through the GraphQL endpoint and can be consumed by any head technology such as Next.js, ASP.NET core, Angular, Vue or React.

Developers and System Administrators can manage the XM Cloud instances and deploy the custom CM (Content Management) customizations using the “build and deployment services” as well as the Deploy App that provides the functionalities via UI.

For reference, please check the official documentation here.

Now let’s put our hands to work

Creating the XM Cloud project and Site

The first step of course would be to login into the XM Cloud portal and create a new project.

Create project wizard

We can now start from a template or from existing code, I’m selecting “Start from a starter template” as I want to use the XM-Cloud Foundation project.

Step 1
Step 2
Step 3 – Integration with other providers to come
Step 4
Step 5
Step 6
Deployment Logs

Time to grab a coffee and by the time you’re back most probably the project would be ready, if that’s not the case, just have a look at the logs so you get a better understanding of what is going on there.

Deploy completed in 7 minutes

Now the deployment is done and our XM Cloud instance up and running.

Pages

If we have a look at Pages, we see the defualt Sitecore homepage, but the tree looks empty. So, let’s create our first site. For that, we go to the “Sites” tab and click on “Add your first website“:

We choose for this example the “Basic Site” template:

We give it a name (mysite) and click on create website, in a few minutes, the site will be ready.

After is done, we can get back to the “Pages” tab and start playing and exploring the new editor.

Components
Responsive view (mobile)

We can now publish the site to the Edge so we can start querying the GraphQL Endpoint:

Project options

Generating the Edge access token

Now that we have the site created and published to the Experience Edge, we have to create our Edge Token so we can set up our local Next.js app and also start querying the edge GraphQL endpoint.

We need now to connect to our XM Cloud instance, for doing that we can use the Sitecore CLI:

dotnet sitecore cloud login
Device confirmation

After you get the code, then we can start using the CLI that is now connected to our XM Cloud instance. Now get the projects list and copy the project id corresponding to the recently created project.

dotnet sitecore cloud project list
Projects list
dotnet sitecore cloud environment list --project-id {project-id}
Environments list

Now that we know the environment id, we can run the script to generate the edge token. Go to the project root folder and run the following script:

.\New-EdgeToken.ps1 -EnvironmentId {environment-id}
Experience Edge Token

We’ve created now the edge token, the script is already opening the GraphQL playground so you can add the X-GQL-Token to the headers and test a query to the home item:

GrapqhQL Playground

Setup the local Next.js project

The first step is to navigate to the FE project (/../src/sxastarter) and duplicate the “.env” file, name it “env.local” that is already excluded from git, so that we avoid pushing changes to environment variables by mistake.

In the newly created .env file, we add the API key, GraphQL endpoint, and app name:

.env.local

Now we are all set to start the next.js app locally and test it. Still in the same folder (/../src/sxastarter) we ran the commands to install all dependencies and then run the app in connected mode:

npm install
npm run start:connected

Open the browser and go to http://localhost:3000

Deploy to Vercel

Option A – Manual

Now that we have the FE app up and running locally, let’s move one step further and deploy it to Vercel.

Login to Vercel, go to https://vercel.com/new, and choose the GitHub option:

We just need to set the environment variables (the same values we already used for the local app) and make sure the root directory is set to “src/sxastarter“.

Click deploy and keep checking logs to make sure everything is going as expected:

The app is now deployed to Vercel

Here we go! The site is now running and hosted in Vercel.

App hosted in Vercel

Option B – Automatic (Experimental Feature)

First, we need to enable the experimental features, click on the settings icon, in the right upper corner and tick the checkbox:

Experimental features

Then we can go to the project settings and click on “Setup Hosting”

Project details

Click on “Create a new Vercel installation” to connect our instance to Vercel:

Vercel connector
Vercel app

Select the options and accept them. Now is ready to go and deploy:

Link to Vercel

Go to Vercel and check its progress, the project is already getting deployed in Vercel!

Deployment status – Vercel
Deployment status – Vercel
Site deployed to Vercel

Done! our site is now live and hosted in Vercel, with only a few clicks, amazing!

This blog post just shows how easy is to get started with XM Cloud, a bit of an overview of what you can expect, and a development workflow from a front-end point of view. Note: For backend development, customizations, etc. I’ll be just spinning up the containers locally and/or working with the Sitecore CLI to pull/push content, more on this later.

Thanks for reading!

References

  • Check out some very useful video series from Sebastian Winter (@lovesitecore) here.

Converting Sitecore MVC sites to Jamstack with Headless Services and JSS – Next.js

In this post I’ll be showing an approach to convert existing Sitecore MVC applications to the Jamstack architecture, it’s time to think about how to modernize our old-fashioned Sitecore apps to benefit from modern tech stacks capabilities like headless, SSG, ISR, multi-channel, etc.

Architecture

Jamstack architecture for existing Sitecore MVC sites is possible because of the ability of the Sitecore Layout Service to render MVC components to HTML, and include them in its output.

Jamstack architecture with Next.js. Ref: here

The publishing and rendering process consists of the following steps:

  1. The Layout Service outputs MVC components as HTML, embedded in its usual service output.
  2. The Layout Service output is published to the Content Delievry with each page/route, allowing it to be queried by Sitecore headless SDKs such as Next.js.
  3. The Next.js application queries the Layout Service output for the route and passes it into one or more placeholder components.
  4. Based on the lack of a componentName property in the layout data, the Placeholder component in the Sitecore Next.js SDK renders the Sitecore component directly as HTML into the pre-rendered document.

Prerequisites

  • Sitecore version 10.2+ – An upgrade of your MVC application would be needed.
  • Sitecore Headless Services module version 19+.

Demo!

To make things easier for this demo, I’m using the “Basic Company – Unicorn” site from the Sitecore Helix examples, you can find the repo here.

The first step is to upgrade the solution to 10.2, you can also find my open PR with the upgrade here.

Then, we need to add the Headless Services to our CM and CD images. You can find the final code here, which also adds on top of it a Next.js RH app image.

At this point, we have our MVC application up and running on Sitecore 10.2 and Headless Services are also installed. We are now ready to start making some changes to the app so we can make it work with JSS.

Prepare the MVC site to be compatible with JSS App

First of all, we need to create our API key in order to allow the Layout Service to communicate through our Sitecore instance. For that, we simply create an item under /sitecore/system/Settings/Services/API Keys

Make sure to keep CORS and controllers to allow * for this demo

To enable editing and static generation support in the JSS app, we have to make the site root to inherit from /sitecore/templates/Foundation/JavaScript Services/App template:

To enable editing support, we need the layout to inherit the template /sitecore/templates/Foundation/JavaScript Services/JSS Layout .

Now, we need to configure the Layout Service Placeholders field. This field determines which placeholder information to include in the Layout Service response data.

Inspect the Layout Service reponse

We can have a look now and analyze the Json we are getting from the Layout Service by visiting the endpoint:

https://www.basic-company-unicorn.localhost/sitecore/api/layout/render?item={97479C6B-BB30-4A15-AFD1-2C89F207E9D6}&sc_apikey={B10DB745-2B8A-410E-BDEC-07791190B599}

Layout Service response

We can see in the response, that we are getting the placeholders we included previously (main, header and footer).

Configure the Sitecore Layout Service to output HTML for MVC renderings

Let’s now go and configure the “Hero Banner” component to render HTML instead of Json:

Done, let’s publish this change and see what we get in the Layout Service response for this component:

So, here we go, we can find the HTML now in the contents. Let’s enable the HTML output on all the other MVC renderings and publish those changes, in the meantime, let’s create our JSS app.

Create the Nextjs JSS app

Let’s open a terminal and navigate to the src folder (..\examples\helix-basic-unicorn\src\Project\BasicCompany). We now run the JSS CLI command to create a new app, here we can choose if we want to fetch data with REST or GraphQL, also the prerendering on SSG or SSR:

jss create basic-company nextjs --empty --fetchWith GraphQL --prerender SSG

The JSS app is now created. Let’s set it up and connect it to our Sitecore instance. Run the following CLI command:

cd basic-company
jss setup

Provide the following values:

1- Is your Sitecore instance on this machine or accessible via network share? [y/n]: y
2- Path to the Sitecore folder (e.g. c:\inetpub\wwwroot\my.siteco.re): ..\examples\helix-basic-unicorn\docker\deploy\website
3- Sitecore hostname (e.g. http://myapp.local.siteco.re; see /sitecore/config; ensure added to hosts): https://www.basic-company-unicorn.localhost/
4- Sitecore import service URL [https://www.basic-company-unicorn.localhost/sitecore/api/jss/import]:
5- Sitecore API Key (ID of API key item): {B10DB745-2B8A-410E-BDEC-07791190B599}
6- Please enter your deployment secret (32+ random chars; or press enter to generate one):

Now we can deploy the config (check the files creates under sitecore/config). For this we run the following CLI command

jss deploy config

Prepare the NextJs App to render our content

Let’s update the Layout.tsx to add our placeholders (header, main, footer):

Also copy the “basic-company.css” from the website folder into the “src/assets” folder and update the _app.tsx with this :

All good, time to connect and test it! Run the following CLI command:

jss start:connected
HTTP://localhost:3000

Yay! visit http://localhost:3000 and you can see the Basic Company MVC site rendered as a JSS App, this is ready to be deployed and make it statically generated, but let’s move one step forward and start converting one of the components to React, as I see this approach to incrementally start your migration to JSS (React).

Experience Editor compatibility

Let’s double-check that our Experience Editor is still working as expected:

Start converting components from MVC (C#/Razor) to Next.js (JavaScript/React) incrementally

Let’s duplicate the “Hero Banner” rendering in Sitecore, change the template to make it a “Json Rendering”, rename it to “HeroBanner” to make it compliant with React naming conventions, and disable the “Render as HTML” checkbox. Also, make sure the “component name” field is set to “HeroBanner”. Then add this new component to the Homepage next to the MVC one.

Duplicated HeroBanner component

Publish the rendering and check again the Layout Service response, now, you should be able to see the two versions of the component, the one in HTML and the Json:

Good! We got the expected results on the Layout Service response, if we go now and refresh our JSS App, we will see that the component is added but still lacking its React implementation:

Create the React component through the component scaffolding

To create the React implementation of the component we created, just run the following in the terminal (always from the JSS App root):

jss scaffold BasicContent/HeroBanner 

Have a look at the files created, make some changes to the React implementation (BasicContent/HeroBanner.tsx)

import { Text, Field, ImageField } from '@sitecore-jss/sitecore-jss-nextjs';
export type HeroBannerProps = {
  fields: {
    Title: Field<string>;
    Subtitle: Field<string>;
    Image: ImageField;
  };
};
const HeroBanner = ({ fields }: HeroBannerProps): JSX.Element => {
  const bannerStyle = {
    backgroundImage: `url(${fields.Image?.value?.src})`,
  };
  return (
    <section className="hero is-medium is-black" style={bannerStyle}>
      <div className="hero-body">
        <div className="container">
          <h1>React!</h1>
          <Text field={fields.Title} tag="h1" className="title" />
          <Text field={fields.Subtitle} tag="h2" className="title" />
        </div>
      </div>
    </section>
  );
};
export default HeroBanner;

Now both MVC and React components are living on the same site, I kept both to make it more visual, but the proper way of migrating would be just replacing the MVC rendering.

I hope you find this interesting, you can find the complete solution here, it’s a fork of the Sitecore Helix Examples and added on top the headless services, Sitecore 10.2 upgrade, a NextJS rendering host, and app.

Thanks for reading!

Ref Official documentation