Skip to main content

Sitecore XM/XM Cloud - Exclude specific Sitecore items from prerendering Sitecore JSS

Hi Team,

Today's post will interest most of the coder and Sitecore technologist who are working in Sitecore JSS apps and want to ignore some paths from prerendering and also want to it to content manage them, so those items which you want to ignore can be in sitecore and everything will work dynamically.

I am going to talk about how to exclude specific pages from being prerendered 

Till now, I believe most of you know how to prerender pages in Sitecore JSS apps using NextJS, Using getStaticProps function, Basically it generates static version of your Sitecore page and prerender it and save it on the server disk, so the loading of the page becomes faster and site performance is improved so i will not cover that and there is a great documentation out there on Sitecore jss site https://doc.sitecore.com/xp/en/developers/hd/19/sitecore-headless-development/prerendering-methods-and-data-fetching-strategies-in-jss-next-js-apps.html 

I will cover the scenarios on "How can you exclude some pages from being prerendered" in Sitecore JSS 10.3

Why you need to exclude pages?

There can be scenarios where you do not want some pages to be generated statically, for example redirect page items, or pages which dynamically changes like after login pages, those should be kept SSR and not SSG.

Talking about the specific scenario where if i talk about redirect page items, if you prerender them, Your NextJS app will fail at build time complaining that "Error: `redirect` can not be returned from getStaticProps during prerendering", in that case you will need to make sure that those redirect items are excluded from the array of pages which "getStaticProps" uses to generate the static pages.

I have a detailed blog post on why "Error: `redirect` can not be returned from getStaticProps during prerendering" error comes even if redirect object is given in "getStaticProps" syntax on Sitecore JSS - Error: `redirect` can not be returned from getStaticProps during prerendering (daivagnananavati.blogspot.com)

Interesting enough? and sounds like a known challenge to you all? Let's get to the solutions

Ignore specific items from being prerendered

There are multiple ways to do one thing in this new world of Sitecore JSS headless and NextJS world and it depends on what version you are but I am talking about Sitecore 10.3 JSS, Because of the different directory structure 

If you read the documentation given on https://doc.sitecore.com/xmc/en/developers/xm-cloud/customize-build-time-static-paths-in-jss-next-js-apps.html you can see the it provides "excludePaths" property in which you can give an array of paths, and those will be ignored from being statically generated, Fair enough, but this will only help when you already have known the path ahead of time, what if you want to exclude items of specific template, so when content author creates item in Sitecore, Our JSS app should automatically ignore it from prerendering?

Solution

Because we know that we can use this "excludePaths" property of "GraphQLSitemapService" and if somehow we fill this property dynamic before the getStaticProps is called, and generate those paths to be ignored dynamically, it will ignore those paths

Solution is GraphQL Search query

So idea is, You write and test query which can only get item path of specific template and make sure it is called before getStaticProps and "excludePaths" property of "GraphQLSitemapService" is filled out, following is the example where i wanted to exclude redirect items and they were created from OOTB (Out of the box) JSS redirect template


query RedirectQuery(
        $rootItemId: String = "<<home item guid>>"
        $language: String = "en"
        $pageSize: Int = 1000
        $after: String
        $redirectTemplateId: String = "<<redirect item template id without {} and "-">>"
      ) {
        search(
          where: {
            AND: [
              { name: "_path", value: $rootItemId, operator: CONTAINS }
              { name: "_language", value: $language }
              { name: "_templates", value: $redirectTemplateId, operator: EQ }
            ]
          }
          first: $pageSize
          after: $after
        ) {
          total
          pageInfo {
            endCursor
            hasNext
          }
          results {
            path
          }
        }
      }

If you run above query in GraphQL editor, It will return all the path of redirect template's item under the home node.


Now, we have the paths, we just want to find a way so it can be ignored during getStaticProps process, so to do that what we will do is we update "graphql-sitemap-service.ts" file and just before fetchSSG method of "GraphQLSitemapService", we will make sure that we update the property "excludePaths" by running a loop and creating an array of all these item which we got from the GQL query, Something like below

async exec(context?: GetStaticPathsContext): Promise<StaticPath[]> {
    if (process.env.EXPORT_MODE) {
      // Disconnected Export mode
      if (process.env.JSS_MODE !== constants.JSS_MODE.DISCONNECTED) {
        return this._graphqlSitemapService.fetchExportSitemap(config.defaultLanguage);
      }
    }
    const excludedPages = await this.GetExcludedPath();
    this._graphqlSitemapService.options.excludedPaths = excludedPages;
    return this._graphqlSitemapService.fetchSSGSitemap(context?.locales || []);
  }

If you see above code has a function which is getting called "GetExcludePath", which is calling above graphQL query and just returning the path of item, and that array we are giving into "excludePaths"

Full code of "graphql-sitemap-service.ts" looks like below

import { GraphQLRequestClient, GraphQLSitemapService } from '@sitecore-jss/sitecore-jss-nextjs';
import config from 'temp/config';
import { SitemapFetcherPlugin } from '..';
import { GetStaticPathsContext } from 'next';
import { StaticPath, constants } from '@sitecore-jss/sitecore-jss-nextjs';
import { gql } from '@apollo/client';

class GraphqlSitemapServicePlugin implements SitemapFetcherPlugin {
  _graphqlSitemapService: GraphQLSitemapService;

  constructor() {
    this._graphqlSitemapService = new GraphQLSitemapService({
      endpoint: config.graphQLEndpoint,
      apiKey: config.sitecoreApiKey,
      siteName: config.jssAppName,
    });
  }

  async exec(context?: GetStaticPathsContext): Promise<StaticPath[]> {
    if (process.env.EXPORT_MODE) {
      // Disconnected Export mode
      if (process.env.JSS_MODE !== constants.JSS_MODE.DISCONNECTED) {
        return this._graphqlSitemapService.fetchExportSitemap(config.defaultLanguage);
      }
    }
    const excludedPages = await this.GetExcludedPath();
    this._graphqlSitemapService.options.excludedPaths = excludedPages;
    return this._graphqlSitemapService.fetchSSGSitemap(context?.locales || []);
  }

  async GetExcludedPath(): Promise<string[]> {
    const EXCLUDE_PAGE = gql`
      query RedirectQuery(
        $rootItemId: String = "<<home item GUID>>"
        $language: String = "en"
        $pageSize: Int = 1000
        $after: String
        $redirectTemplateId: String = "<<redirect item template id without {} and "-">>"
      ) {
        search(
          where: {
            AND: [
              { name: "_path", value: $rootItemId, operator: CONTAINS }
              { name: "_language", value: $language }
              { name: "_templates", value: $redirectTemplateId, operator: EQ }
            ]
          }
          first: $pageSize
          after: $after
        ) {
          total
          pageInfo {
            endCursor
            hasNext
          }
          results {
            path
          }
        }
      }
    `;
    const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
      apiKey: config.sitecoreApiKey,
    });

    const result = await graphQLClient.request<any>(EXCLUDE_PAGE as any);
    const arr = result?.search?.results;

    const pages: any[] | PromiseLike<string[]> = [];
    arr?.map((item: any) => {
      // Fix for SC ticker no CS0387155
      const path = item?.path?.replace('/sitecore/content/<<tenant>>/<<site name>>/Home', '');
      pages.push(path);
    });
    return pages;
  }
}

export const graphqlSitemapServicePlugin = new GraphqlSitemapServicePlugin();


Now, this items will be excluded from prerendering, remember if you have limited items and if they are known at build time, you can also give it directly in excludePath property in array and it will ignore those paths from being prerendered. 

NOTE: In a GraphQL above, I have used "path" and not "url { path }", There is a reason to it, because there is a bug if I use url { path } which I have explained in my blog post 


I hope this will help many of you, also refer to following blog post where I faced issues and also blogged about those specifics.











Comments

Popular posts from this blog

High CPU to completely normal CPU - SXA issue, SXA pages not loading in mobile device

  Hi Team, Today i am going to share one of the nightmarish issue with you all, We are having Sitecore 9.1.1 hosted in azure PaaS environment Our site was working just fine and no noise, but we have been working on a feature release where 7-8 months of development needed to be released to production, Big GO LIVE event right?  Also to make the development smoother we also introduced BLUE/GREEN deployment slots in the same release, so we can easily SWAP slots and go live Everything went well, we went live, we even did load and performance testing on our staging and pre-prod and we were confident enough of results Very next day we started getting "SITE DOWN" alerts, and also product owners and clients mentioned that site is very slow for them in US time and in our morning when we were accessing it, it was working lighting fast so we were clue less at start, but we started digging  1) First thing caught our eyes were HIGH CPU spikes, in US time, also without any traffic CPU u...

Set up leprechaun code generation with Sitecore XM Cloud Starterkit

Hi Sitecorians, It has been amazing learning year so far and with the change in technology and shift of the focus on frontend frameworks and composable products, it has been market demand to keep learning and exploring new things. Reasons behind this blog Today's topic is something that was in my draft from April-May, and I always thought that there is already a good documentation out there for  Leprechaun  and a blog post is not needed, Until I realized that there was so many of us facing same kind of issues and same kind of problems and spending same amount of time, That is where I thought, if I could write something which can reduce that repetitive troubleshooting time, That would really help the community. 1)  In a project environment, if we get into some configuration issues, we resolve them, we make sure we are not blocked and continue, but if you think same issue, same step and same scenario will come to other people, so if we can draft it online, it will help othe...

An error occurred while receiving the HTTP response to This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

You have noticed many times that everything was working fine and suddenly the below error starts coming and you find no way to work it out An error occurred while receiving the HTTP response to This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. The reason for this is the receiving size of WCF service is smaller then the data which is coming from service It was working before because it was small,So you will have to try to increase the receiving setting in your end point,Possible settings can be following maxStringContentLength="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxArrayLength="2147483647" That would definately help you!!!