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

Start your commerce solution in minutes with Vercel, Next.js Commerce template, and the new Sitecore OrderCloud® integration – Part II

In my previous post, I’ve shared how easy is to get your Next.js Commerce solution up and running powered by Sitecore OrderCloud®. Please have a look at the previous post before getting into this reading as this is a continuation that focuses on the development environment, the local solution setup, and the CI/CD approach.

Local solution setup

Let’s get back to our Github repo and clone it locally, then open it on Visual Studio Code.

Starter kit solution on VS Code

We have our solution cloned locally, let’s open a terminal now and run npm install to install all dependency packages needed by the solution.

npm i

Vercel CLI

The Vercel’s command-line interface enables instant cloud deployment and local development.
To learn more, visit the official documentation, let’s get started now by installing the CLI:

npm i -g vercel

Now we can just run “vercel link” to link our local repo with the Vercel project.

Use your Vercel credentials to login, choose your scope, and Vercel will magically recommend the proper project to link to. Veryfi all this information and proceed, if everything went good, you should see a green tick saying your project is now linked.

vercel link

Now we need to get in our local all the environment variables we got created on Vercel:

Environment Variables needed for communicating with the Sitecore OrderCloud API

We can speed up the process of creating those variables locally by using the Vercel CLI command “vercel env pull

You can see now that a new .env file got created and contains all the variables we need:

environment variables locally imported

Also, the previous step created the “vercel” folder where we can find the project.json configuration file.

Let’s test it out!

We got now everything in place, so let’s just run the app locally in develop mode by running “npm run dev

npm run dev

Pum! Another unexpected exception 😦

After some analysis, I noticed there is an issue in this file (packages/commerce/src/config.cgs), while trying to build the path to the next.config file under packages:

const commerceNextConfig = importCwd(path.join(provider, 'next.config'))

I just updated with the hardcoded path and it seemed to fix the issue. Check this open issue for more details, or you can also refer to this PR that seems to be fixing the issue.

Build succeed this time 😉
Storefront site at localhost

The app is now running locally in development mode and connected to Sitecore OrderCloud.

Let’s test our CI/CD

Let’s make a quick change on our project, test it locally, push it to Github and then deploy to Vercel.

So, in order to make some changes to the homepage, open and edit the pages/index.tsx file:

As you can see, I’m moving the marquee before the grid, and adding a heading text (note that you’d need to first add the import):

Here we go! As we’re running the app on development mode, we get feedback instantly, so get back to the local site in the browser and refresh it:

The marquee is now at the top and right after the heading text we added (“Sitecore OrderCloud Rocks!“).

Cool, so now that we’re fine with our local test, we commit and push to the repo…

Just verify we pushed the changes to Github

Go back to the Vercel portal and check that the build got automatically triggered 🙂

Amazing, isn’t it? Our changes are now deployed and pushed live to Vercel:

That’s it! The main reason behind this post was to show how easy is to get started with Sitecore OrderCloud, Next.js Commerce Templates, and Vercel. The starter kit gives you everything to start working with and for start learning this new technology stack as well. So don’t waste time and go try out this by yourself!

I hope you found it interesting, and see you soon with more Sitecore related stuff!

Start your commerce solution in minutes with Vercel, Next.js Commerce template, and the new Sitecore OrderCloud® integration – Part I

In this post, I’ll describe the steps to get a full development environment from scratch, using the Next.js Commerce template integrated with OrderCloud and deploying to Vercel.

Sitecore OrderCloud®

Sitecore OrderClooud is an API-First, headless cloud platform for B2B, B2C, and B2X commerce solutions. It powers custom e-commerce experiences, order management, and B2B marketplace applications for some of the world’s most well-known brands.

If you don’t have your account yet, go here and create one, you can sign up for free!

Vercel – Next.js Commerce

Next.js Commerce is an all-in-one React starter kit for high-performance e-commerce sites. You can clone, deploy, and fully customize with a few clicks.

And again, if you don’t have an account yet, go here and create one, you can sign up for free!

If you want to learn more about Next.js, don’t hesitate to go through the official documentation, it’s really good and useful.

Let’s go and get it done!

The first step is to login into Vercel and start a new project, then we just need to choose the Next.js Commerce template:

The Vercel templates

After we choose the Next.js Commerce template, we give the Git repo a name, and click on create:

Creating the starter kit Github repo

You can now go and check what Vercel has created for you in the Github repo:

Github

If you have experience developing Next.js apps, this repo would look familiar to you.

If you look at the readme file, you will see there is a demo site powered by Sitecore OrderCloud®!

Let’s get back and continue with our setup!

We have our Github repo, let’s skip the add integrations step for now and go straight to the deploy:

Build/deploy running for the first time…
The project got deployed to Vercel

Yas! your project got built and deployed to Vercel, you can now go and browse it (amazing isn’t it?)

The Commerce site is already up and running!

Setting up the Sitecore OrderCloud® integration

The site you’re browsing now already has some content, but as we are not integrating with any e-commerce platform yet, is just statically stored and generated. Let’s change that and switch our e-commerce solution to be powered by Sitecore OrderCloud®.

For doing that, go back to your Vercel project and then go to the Settings section, then click on Integrations and search for the OrderCloud by browsing the Marketplace

Browsing the integrations Marketplace

You would now see the Sitecore OrderCloud integration under the Commerce section:

SitecoreOrderCloud integration

Then click on Add Integration and choose your Personal Account as Vercel Scope. Click on continue and then select the project we just created for the OrderCloud integration.

Add the integration and then login to your Sitecore OrderCloud account.

In the next step, you’re prompted to choose your OrderCloud Marketplace. You would see that you can choose an existing one, but this time I want to create a new one “Seed new Marketplace (ID: “NEW”)

You can see the progress and logs, yeah Vercel is creating everything on OrderCloud for you!

Get back now to your Vercel project, settings and check the Environment Variables. You can see the key values created in the previous step:

Check your Sitecore OrderCloud® Marketplace

Now, login to Sitecore OrderCloud, go to Marketplaces and you should be now able to see the newly created “Vercel Commerce

Let’s try this out. Go to the API Console and then select “Catalogs“, click on send to make the API call, and check the results:

Copy the ID (solitary-storefront) so you can now browse categories by this Catalog ID:

Let’s browse the products now, copy the category ID (shirts) and make the request from the Products section:

Time to deploy it!

We just checked that the data is created on OrderCloud and we can easily query the API to get the results. Our Vercel integration is ready and now is time to deploy it so get our app consuming OrderCloud data.

just get back to your Vercel project, go to the deployments section, select the latest green one and redeploy it:

Uuuups! the build failed this time… That’s weird and unexpected, but let’s check logs and see what’s going on:

As I mentioned in the previous step, the OrderCloud integration created the environment variables to make the app communicate with OrderCloud.

Ok, that’s odd, it seems the “COMMERCE_PROVIDER” variable is not set properly. Let’s follow the logs recommendations and update it from “ordercloud” to “@vercel/commerce-ordercloud“. Save it and redeploy:

Yas! it seems to be good now, and the build is going good, you can also see in the logs how the site is being statically generated but making requests to the OrderCloud API this time:

You can see now our site getting data from OrderCloud!

Let’s make a quick update on OrderCloud and check changes in our storefront.

Let’s make an update on the Black Hat product. For that, go to the “Products” search for the “Black Hat” and then choose “PUT Create or update a product“. Change the price from 80 to 40, and the name to “OrderCloud Black Hat“:

We can query again to make sure the price got updated:

Get back to the site and check the updated product:

We have now our e-commerce solution deployed to Vercel, powered by Sitecore OrderCloud, and our Next.js app created on our Github repo.

In the next post, I’ll be exploring and sharing the local solution setup and the CI/CD so you can get an idea of how easy is to start building your solution with this tech stack.

I hope you found this post useful!

If you are interested in this topic, please don’t hesitate to watch the full demo example from Rob Earlam on YouTube.