Wednesday 20 April 2022

Sitecore Next.JS SSG + SSR (same site)

Recently I was working with a client who was implementing a Next.JS app, and wanted the benefits (ie. speed) of SSG but with a few exceptional pages using SSR (for Forms etc.). Note in the Sitecore Next.JS Forms documentation, there is an unfortunate requirement (currently at least) of: "you are server-side rendering the route displaying the form".

So SSG + SSR in one Next.JS app, no problem!  

There are a couple of considerations, however, so let's look at the steps involved:

  1. Create your Next.JS app with --fetchWith REST --prerender SSG (we'll add an exception for the SSR page(s))
  2. Now that you've got an app create your Next.JS Form
  3. Add a page with your form on it, both in Sitecore and code (eg. src\pages\contactus.tsx). Make sure you're using getServerSideProps() for SSR.
    • If we navigate to the page at this point you should actually see the (incorrect) content (from the homepage). 
    • Debug the server-side code and take a look at the sitecoreContext and you'll see it's actually resolving as the root path '/'
  4. Looking at the Sitecore Documentation for Routing we can see lib\page-props-factory.ts is responsible for setting the sitecoreContext and fetching the layout data. Look around line 91 (headless v19) and you'll see a call to extractPath(context.params)
    • Let's compare our context for the styleguide:
      • {
            "defaultLocale": "en",
            "locales": [ "en", "da-DK" ],
            "locale": "en",
            "params": {
                "path": [ "styleguide" ]
            }

        }
    • vs our context for our SSR page:
      • {
            "defaultLocale": "en",
            "locale": "en",
            "locales": ["en", "da-DK"],
            "query": {},
            "req": {...},
            "res": {...},
            "resolvedUrl": "/contactus"
        }
    • So we'll need to update our line which sets the path:
      const path = context.resolvedUrl ?? extractPath(context.params);
  5. Finally, let's not forget to update our getStaticPaths / sitemap to exclude our SSR pages

Enjoy your speedy headless Sitecore site using both SSR + SSG!