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

One or more exceptions occurred while processing the subscribers to the 'item:creating' event

I was recently installing the packages from one of the QA environment to my local Sitecore instance, "Media library package" to be precise, And it started giving me this below error One or more exceptions occurred while processing the subscribers to the 'item:creating' event Looking at the sitecore logs, it gave me more info on the context and the actual inner exception was following Solution: 'Name' should consist only of letters, digits, dashes or underscore Now it was evident that some of my file names were violating the naming rule, I could see in the log just before exception from where the installer stopped creating items, and that file name had round braces "(" and ")" at the end of it, with my surprise I was able to create the item with those name in the content tree, but below was the solution for it, Solution I am using SC 9.0.1 and in that Go to Sitecore.Marketing.config file residing in "App_Config\Sitecore\Mar...

401.1 Unauthorized with windows authentication error code 0xc000006d

How many of you have faced this hosting issue when you do everything what it takes to run the site with windows authentication but still you are getting the same error again and again? If you think you also have faced the same issue and you tired of reading MSDN KBs for it and still have not found the issue (If KB has solved the issue, well and good, if not you can try this trick),Please Read below Typical scenario In typical hosting with IIS, i did every possible things like enabling windows authentication, changing it in web.config, configuring connection pool, authorization rules, it asks me for window authentication login and despite of entering correct credentials it always fails and keeps on asking for login, and when pressed cancel it gives 401.1 with 0xc000006d error code Solution (Which worked for me at-least after trying for almost 6-9 hrs) You need to change the Loop Back Check in registry so that it allows the host names which you are giving in url are allowed and au...

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!!!