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
Post a Comment