Sitecore for JavaScript developers in a hurry

Alex Shyba
by Alex Shyba
Headless CMS & front-end engineering

There has been a lot of buzz and excitement about Sitecore as a Headless CMS and different capabilities in this area that exist now in General Availability, such as Sitecore Experience Accelerator and Sitecore Services Client, as well as in Tech Preview, such as Sitecore JavaScript Services (JSS).

While Headless CMS is a cool and all, one of the primary goals of Sitecore JSS was to add a proper first-class interface for JavaScript developers and enable using modern JS tech to build websites and web apps powered by the Sitecore Experience Platform. So I’d like zoom in a little bit on this original goal and break it down into major highlights. I believe that this set of capabilities makes Sitecore JSS quite a special and unique toolkit. Ok, here we go…

Developer Experience

It’s no secret that great Developer Experience (DX) is paramount for developers. The smoother and more pleasant it is, the happier and more productive you are. So the good news is that Sitecore JSS is well-aligned with the modern DX expectations of front-end developers and should be quite refreshing for ASP.NET folks transitioning to JavaScript UI libraries and frameworks (React/Angular/Vue).

It’s important to note that the Sitecore JSS toolkit is not pushing you to use any developer toolchain; instead, it augments your tooling of choice with Sitecore-specific CLI providing ability to scaffold the app, deploy a component or the whole app to Sitecore CMS.

Here is a quick video showing how easy it is to get started with Sitecore JSS:

Use your favorite JS UI library or framework

Currently supported once are React.js, Angular, and Vue.js, with React Native being experimental. Most concepts are universal, and it is entirely feasible to add support for your favorite library or framework, if it’s not in the list. This helps making JSS adaptable to whatever new hot JS tech comes in 2020 ;)

The jss CLI is consistent across React.js, Angular and Vue.js:

Disconnected from CMS during development

It’s a real gem for front-end developers that want to get started without too much ceremony. Sitecore JSS enables cross-platform app development thanks for universal JavaScript - so you can use any OS, any IDE. The sample apps used for jss create come wired up with a mocked Sitecore Layout Service giving you the ability to start development without access to a Sitecore installation. Simply do jss start and the app will be built and served locally by webpack. This approach fits well in the front-end lead projects, for faster experimentation and reducing the “CMS integration tax.”

“Deep SDK”

Sitecore JSS SDK, which consists of a set of modules on npm, not only provides the bindings to the server-side Sitecore Layout Service, Content and Dictionary APIs but also brings the coveted <Placeholder /> component to React.js, Angular and Vue.js. This is not only a focal point of the Sitecore integration but also is a handy component composition facility to JavaScript developers.

Here is how it works in a nutshell. Instead of statically placing the components within other components and therefore hardcoding the component composition as shown below (using fake JSX just for the illustration purposes only. While React is featured as a sample here, same placeholder mechanics applies to Angular 5 and Vue.js libraries):

<BodyContainer>
  <Header>
    <Jumbotron title="hello" />
  </Header>
  <Carousel />
</BodyContainer>

you can define the placement rules in JSON or YAML on route files under /data/routes:

# /data/routes/en.yaml for the 'Home' route
name: home
placeholders:
  # 'body' is a placeholder name
  body:
  - componentName: Header
    placeholders:
      # 'header' is a nested placeholder name
      header:
      - componentName: Jumbotron
        fields:
          title:
            value: hello
  - componentName: Carousel

As you can see, the placeholders support nesting and such witchcraft as Dynamic Placeholders to support more complex nesting scenarios like tabs.

Now you can replace previous static placement with the <Placeholder /> from @sitecore-jss/sitecore-jss-react, so it can inject the child components dynamically within <BodyContainer /> component:

<BodyContainer>
  <Placeholder name="body">
</BodyContainer>

Notice the name prop on Placeholder corresponds to the key in JSON/YAML declaration above.

…we can do the same within <Header />:

<Header>
  <Placeholder name="header">
</Header>

Notice that <Jumbotron /> requires the title prop to be passed in:

<Jumbotron title="hello" />

Now the <Placeholder /> will be taking care of it and will pass the value hello to dynamically injected instance of the <Jumbotron /> component:

# extract from 'Home' route placement
- componentName: Jumbotron
  fields:
    title:
      value: hello

After the app is deployed and integrated with Sitecore, this dynamic component composition will be driven by Sitecore’s Layout Service and same output you mocked up in ‘dev’ using JSON/YAML is now delivered via HTTP API endpoint to your app.

This allows for the component composition to be controlled by a Sitecore business user via Experience Editor, where they can not only change content and move components around according to constraints and create new pages, but also set personalization rules, launch multivariate testing, etc.

This means that your business users (authors, marketers) continue being in complete control over the digital property. Sitecore’s Contextual Content Delivery engine takes care of the rest and you as a developer don’t have to do anything else to enable that. In other words, you are empowering the business users while having fun building the app using latest cool JavaScript tech, being entirely detached from the Sitecore CMS during development. You don’t have to compromise!

Code-first development

The Code-first development model empowers front-end developers to do more and shape the contract for the presentation components and routes in JavaScript.

Adding a new component

In order to properly register our <Jumbotron /> component from the example above, we need to add a Jumbotron.sitecore.js file under yourapp/sitecore/definitions/components and specify which fields we need along with other relevant meta-data:

import { addComponent, CommonFieldTypes } from '@sitecore-jss/sitecore-jss-manifest';

export default (manifest) => {
  addComponent(manifest, {
    name: 'Jumbotron',
    fields: [
      { name: 'title', type: CommonFieldTypes.SingleLineText }
    ],
  });
};

The only required property is component name. Since we expect a prop called title and we want it to be managed in Sitecore as field, we need to register it and map to appropriate field type (SingleLineText in our case).

@sitecore-jss/sitecore-jss-manifest is written in TypeScript, so you have a great Dev Experience creating these definitions:

Adding a new field

These manifest declarations are translated into multiple native Sitecore item artifacts during app import process triggered by jss deploy package, therefore streamlining the process of component registration significantly.

Instead of deploying the whole app, you can leverage a handy jss deploy component command descsribed in more detail here.

Adding a new route

Besides registering the components, you are able to add new routes, which is as simple as:

  1. Add new .yaml or .json route file under /data/routes (depending on your app configuration), let’s call it ‘about’.

  2. Add the component placement rules:

# placing Jumbotron directly to 'body' placeholder bypassing the 'Header' component
name: about
placeholders:
  body:
  - componentName: Jumbotron
    fields:
      title:
        value: About Us

JSS also supports sharing component placements across multiple routes.

That’s it! Most sample apps are setup with wildcard routing, so you should be able to go to http://localhost:3001/about and see the page render.

The Code-first model is optional and may not make sense for all the use cases. DM me if you want to talk through your project specifics and get a recommendation.

WYSIWYG editing and preview for your JavaScript app

Yeah, I know WYSIWYG is so 2008 :) That being said, the CMS industry invested into this capability along with contextual preview functionality, so why to give it away for a web site/application?

Another gem that is unique to the Sitecore’s approach to hybrid headless is the ability to render the JavaScript app within the Content Management environment via a custom node.js based rendering engine.

This enables your web site/app built in 100% JavaScript to be visually editable within Sitecore Experience Editor effortlessly:

Besides editing content on existing pages, your business users can create new ones, set personalization and multivariate testing.

On top of that, you can optimize your components for the “editing” mode, as you have access to context.pageEditing=true from API. “Advanced sample app” is leveraging this technique to hide the tabs in editing mode.

Tracking/analytics

With the page tracking enabled out of the box, any goal or page event associated with the page is triggered on the Sitecore Content Delivery automatically.

If you have needs for proactive tracking (like goal registration on client-side button click), you may want to consider using FXM alongside with JSS or roll your own API endpoint.

A diverse set of open-sourced samples

Being wired for both client-side and server-side rendering, these sample apps provide a non-authoritarian way of showing how you can put together a JavaScript web app in either React, Vue or Angular and show you the “Hello World” and more full-featured sample apps too.

Introduction of GraphQL to the Sitecore ecosystem

Sitecore JSS introduced another impressive capability recently - Sitecore.GraphQL, an API framework built on an outstanding open source project called GraphQL.NET.

It comes with a provider implementation on top of Sitecore Content APIs and with a sample app wired with Apollo Client. GraphQL is all you need to get all kinds of data from Sitecore CMS and do it in a most efficient and pleasant experience to date:

As GraphQL is going mainstream, this is a highlight capability enabling building next-gen apps with max efficiency, productivity, performance and real-time capabilities.

GraphQL deserves a special blog post series, to be honest. I’d highly recommend checking out this resource as well as Kam’s presentation at SUGCON 2018 specifically on Sitecore.GraphQL. It is an immensely powerful technology and should be music to the ears of JavaScript developers.

There is just too much good stuff in there, so I’d say my favorite highlights of Sitecore.GraphQL specifically are:

  1. Ability to query strongly typed items. Every data template in Sitecore has a type registered in GraphQL schema, how cool is that?
{
  item(path: "/sitecore/content/home"){
    name
    // SampleItem is a data template, so we can query 'title' and 'text' directly
    ...on SampleItem{
      title {
        value
      },
      text {
        value
      }
    }
  }
}
  1. It’s a framework, so you can wrap any existing api with it.
  2. Comes with a baked in GraphQL IDE, which is based on graphiql.
  3. Integration with Sitecore Layout Service, so you can access the components and datasource content, not just content items and fields, making it ideal companion for other Sitecore JSS capabilities.
  4. Very lightweight nature of the module and no dependencies on any other Sitecore components.

Physically decoupled architecture

Ok, this is probably relevant for IT folks and architects, but it’s such a departure from the traditional Sitecore architecture, that it is a shame if I don’t feature this point.

JSS enables you to opt out from deploying your app to the Sitecore Content Delivery servers and therefore turning those servers into leaner & meaner pure content delivery servers with API endpoints for Layout, Content and Dictionary Services as well as the oData Item Service, which you can use together with JSS.

This gives your organization an advantage to have an explicit API boundary for your Sitecore deployment and use it truly as a platform, consuming the APIs from within your app layer in JavaScript:

Physically decoupled architecture

More specifically, this unlocks the following capabilities:

  1. Deploy your app practically anywhere.

    Your app layer is deployed to a separate often more cost-effective node.js services like Heroku (if you need Server-Side Rendering) or to a CDN if client-side rendering is sufficient.

    This gives you more dials to work with in scaling your app, as you can scale node.js servers separately from more expensive Windows-based Sitecore CD servers. In case of CDN-based deployments, this gets even better, as you are offloading rendering to the client and use Sitecore CD servers only for content fetching over HTTP.

    At Altola, we are a big fan of this approach, as on top of the benefits highlighted above, this gives us the ability to use Netlify, a JAMstack platform to deploy anything we build in seconds and do it continuously, and have a globally available preview instance. When the app is ready for integration with Sitecore, it’s as easy as running jss deploy package.

    Teaser: more on JAMstack + Sitecore + Netlify in an upcoming blog post :)

  2. Have more freedom and wiggle room on the front-end as you are less dependent on the Sitecore CMS specifics in your app layer.

  3. Have different deployment strategies and cadence for updates or new features targeting the Sitecore platform and your app, since those are physically isolated.

  4. Easier and more lightweight deployments, since the app is a set of .js and .css files bundled together (no binaries that will undoubtedly restart your Sitecore Content Delivery web app in production which may cause all sorts of side-effects), it makes it super straightforward to deploy and do it continuously.

Progressive Web Apps? Why not!

Finally, because Progressive Web Apps (PWAs) are web apps that have some characteristics of native mobile apps, Sitecore JSS enables you to have those fully integrated with the Sitecore Experience Platform. As PWAs are going mainstream and support for PWA basics in iOS is already here, considering this technology is crucial for your mobile strategy.

I am looking forward to diving deeper into PWAs and Sitecore JSS in upcoming posts, as it’s an exciting new promising technology and there are many use cases to cover like offline, personalization, tracking and analytics.

Next steps?

If you haven’t tried yet, take Sitecore JSS for a spin, my hunch is that your are gonna like it! The docs and open source samples are a great way to get going!

If you need more assistance and support with your JSS project, we can help. One of the services we provide at Altola is a Sitecore JSS boot camp, which you can custom tailor to your needs. If you want to learn more or need ad-hoc assistance, I’d love to chat, and you can book time with me here.

Until next time!