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

Why SitecoreAI - Getting into the shoes of the customer how to select right CMS

Hi Team, Lately, I have been talking to lot of our customers / potential customers and having pre-sales demos where one question always comes is "Why Sitecore" ?  Now this question can be for any product which is out for sell. And as a technician I always get into product technical features, but at the same time as a pre-sales guy, it also makes me think, surely all competitive products have same features, so definitely answer to this is not in the technicalities.  If you step back and think, we are also a customer in our daily life and buy lot of things, what is that process we go through? When we buy, how can your customer decide if this is a right fit for you or not, why we select A over B? Is it price? is it service? Is it a brand? Is it about features? Is it about brand loyalty?  When it is a technical product, I am sure it cannot start with the technicalities of the product or selecting product itself, 100% not, I feel decision is always business strategy first and ...

Hell of sitecore aliases pipeline breaking the site with 500 error

Hello Friends, I belive this blog post is very important for everyone because, It has some very serious effect on working of your headless website, i will share my experience what we faced and how we resolved it Issue we started facing Our site started giving "Key cannot be null or empty" with YSOD like following  Side affect Because of this 500 error, Our site pages were showing 500 custom error page intermittently and our MAU (Monthly Active User) drop rate increased. Sitecore KB There is already Sitecore KB article talking about this error but the patch which is provided on this link is confusing as well as very huge and it could bring other issues along with it as that upgrade patch also has lot of other things too which i did not want to introduce in our stable CMS. Known Issues - Retrieving the child items of resource items is not thread-safe Observation Though the surfaced exception was looking similar and giving same error and behavior given on this article, We looked...

Zero to Hero - A real life RCA of exact issue in Sitecore Managed Cloud environment

Hello All, The purpose of today's post is to share a real life burning and escalated scenario which was new to me and how did I approach it and how big the escalations were and what was the outcome Sitecore's goodwill was at stack not because Sitecore is not capable of handling it but just because our environment was Sitecore Managed Cloud, and any issue that comes if its infra, back end code, front end code will be first pointed as Sitecore issue and that is where our consultancy and experience will play a role to prove that it is not Sitecore issue.  Issue we faced Out of the blue our site started giving "504 Gateway Time-out", and it was reported that almost everyone is getting this error, but when we used to browse the site, everything looked good and never 504. 504 Gateway Time-out error tells that, That the request went to Content Delivery servers of Sitecore from gateway, but gateway did not get response in time from those CDs and hence it gave time out error. ...