Switch the pre-rendering method in a JSS Next.js app
You can choose the initial pre-rendering form when creating the JSS Next.js app with the optional prerender
parameter. If you omit the parameter, the application is optimized for static site generation (SSG) by default. For example:
npx create-sitecore-jss --templates nextjs --appName my-nextjs-app --prerender {SSG|SSR}
The JSS Next.js application comes with an optional catch-all route defined in <src>/pages/[[..path]].tsx
. The route can be optimized for either static site generation (SSG) or server-side rendering (SSR).
The route file is created, based on the value you provide for the --prerender
parameter with the functionality for fetching data for SSR or fetching data for SSG.
After creating the application, you may wish to switch the pre-rendering form or use both types of data fetching for hybrid rendering.
To switch the JSS Next.js application from SSG to SSR:
-
In the file
<src>/pages/[[..path]].tsx
, remove the functiongetStaticPaths
. -
In the file
<src>/pages/[[..path]].tsx
, rename the functiongetStaticProps
togetServerSideProps
and remove therevalidate
property from the object returned by the function. -
Optionally, delete the folder
/<src>/lib/sitemap-fetcher
.
To switch the JSS Next.js application from SSR to SSG:
-
In the file
<src>/pages/[[..path]].tsx
, define thegetStaticPaths
function, as follows:RequestResponseexport const getStaticPaths: GetStaticPaths = async (context) => { if (process.env.NODE_ENV !== 'development') { // Note: Next.js runs export in production mode const paths = await sitemapFetcher.fetch(context); return { paths, fallback: process.env.EXPORT_MODE ? false : 'blocking', }; } return { paths: [], fallback: 'blocking', } ;};
-
In the file
<src>/pages/[[..path]].tsx
, rename the functiongetServerSideProps
togetStaticProps
and add therevalidate
property to the object returned by the function. For example:RequestResponseexport const getStaticProps: GetStaticProps = async (context) => { const props = await sitecorePagePropsFactory.create(context); return { props, revalidate: 5, // In seconds notFound: props.notFound, // Returns custom 404 page with a status code of 404 when true }; };
-
In
<src>/lib
, copy the foldersitemap-fetcher
from the app template repository.