Walkthrough: Customizing build-time static paths in JSS Next.js apps
For very large websites with many pages, products, or articles, the static generation of all the pages might take a long time. You can reduce the build time of your static-generated application by excluding some types of pages/items from static generation.
You can achieve this by using a customized sitemap-fetcher in the getStaticPaths function to modify the list of page paths that are statically generated at build time.
This walkthrough describes how to:
-
Create a custom sitemap service.
-
Create custom sitemap fetchers to customize lists of static paths.
Create a custom sitemap service
You can extend the class GraphQLSitemapService and the interface GraphQLSitemapServiceConfig to allow you to exclude a particular item type:
-
In
src/lib, create a new filesitemap-service.ts. -
In the new file, import the class
GraphQLSitemapServiceand the interfaceGraphQLSitemapServiceConfigfrom the Sitecore Next.js SDK. -
Extend the
GraphQLSitemapServiceConfig, add an additional option to the service configuration: -
Sitecore Delivery Edge requires a valid ID in the search query. For those instances where you will not use the
excludeItemIdoption, you will need to provide a valid, but empty, id. Declare anemptyIDconstant: -
Extend the
GraphQLSitemapServiceclass and override thequerygetter such that, if you provide an ID forexcludeItemIdit will not return items of that type:NoteWe provide
$excludeItemId: String = "${this.options.excludeItemId ?? emptyId}"in the query parameters , as well as the condition{ name: "_path", value: $excludeItemId, operator: NCONTAINS }to thes earchquery.
Create custom sitemap fetchers to customize lists of static paths
With the new sitemap service in place, you can now add sitemap fetchers that suit your needs.
-
In
src/lib/sitemap-fetcher.js, import the necessary libraries, including your new sitemap service:
You can now use the refactored sitemap fetcher to customize the list of static paths for the dynamic routes in your app.
Fetch all pages, excluding some item types
You can use your new ExtendedSitemapService to create a sitemap fetcher that excludes specific item types from the list of static paths.
For example, to fetch all pages except Products:
-
In
src/lib/sitemap-fetcher.js, implement aRootSitemapFetcher: -
Export an instance of
RootSitemapFetcher: -
In your the file
src/pages/[[...path]].tsx, import the instance of theRootSitemapFetcher: -
Modify / add
getStaticPathsto use therootSitemapFetcher:
Fetch only products
You can use the new ExtendedSitemapService to fetch only a specific type of item.
For example, to fetch only Products:
-
In
src/lib/sitemap-fetcher.js, implement aProductSitemapFetcher, to only return product paths: -
Export an instance of the fetcher:
-
In the file
src/pages/products/[[path]].tsx, import the instance of theProductSitemapFetcher: -
Modify / add the
getStaticPathsfunction to use theproductSitemapFetcher: