Static pages and revalidation
Contents
In this chapter you will learn about NextJS' static site generation capabilities, and how Enonic triggers re-generation of pages when publishing.
Introduction
Your NextJS front-end is configured to use Static Site Generation (SSG), which basically means you get lightning fast pages, but adds an additional compilation build step .
For more information visit the Next.js SSG documentation.
Task: Activate prod mode
So far, you have been running Next.js in dev mode.
By starting Next.js in prod
mode, the application is automatically optimized, and in our case, pages get pre-rendered statically before the server starts.
Remember to stop your existing Next.js dev instance before you continue. |
-
Start Next.js in prod mode:
npm run prod
This will take a while longer as when compared to dev mode.
-
Verify by pointing your browser to http://localhost:4242, you should now see the published items, just like in dev mode. Only this time, they will be much faster. Sweet!
Task: Fixing preview
With Next.js now running on a different port, Content Studio preview will stop working.
-
Fix the preview by adding a Next.XP configuration file, with the following content to your sandbox:
The configuration files are located in your sandbox home directory, which can be found in your users home directory as .enonic/sandboxes/<your-sandbox>/home/config/
.com.enonic.app.nextxp.cfgnextjs.default.secret=mySecretKey nextjs.default.url=http://127.0.0.1:4242
-
Verify that the preview is working in Content Studio.
Content Studio uses Next.js' preview mode, which automatically bypasses static pages - giving you a fresh preview of your draft content.
Task: Test page invalidation
With all pages now being cached as files, Next.js must be instructed to re-generate the pages when a change is published.
Edit your front-page, and publish the changes. This will trigger a revalidation hook, which is built into the Next.XP app.
The page should now get updated at http://localhost:4242
- more or less instantly.🎉
What happened?
In addition to handling previews, the Next.XP app automatically triggers revalidation of all pages when it detects the publishing event.
You should also be able to tell from the Next.js log that the revalidation was triggered. |
A look at the code
Static Site Generation is controlled within the content page handler. There are essentially two important functions:
-
getStaticProps()
- instructs Next.js to render static output -
getStaticPaths()
- This function will be used by Next.js at build time to create a list of pages to compile before the server starts.
Below, we explain the details of the code:
import {GetStaticPathsResult, GetStaticPropsResult} from 'next';
import {Context, createResponse,fetchContent,fetchContentPathsForAllLocales, FetchContentResult} from "@enonic/nextjs-adapter";
export async function getStaticProps(context: Context): Promise<GetStaticPropsResult<FetchContentResult>> { (1)
const path = context.params?.contentPath || [];
console.info(`Accessing static page (locale=${context.locale}) ${context.preview ? '(preview) ' : ''}at: ${path}`);
const props = await fetchContent(path, context); (2)
// HTTP 500
if (props.error && props.error.code === '500') {
throw props.error
}
return createResponse(props, context); (3)
}
export async function getStaticPaths(): Promise<GetStaticPathsResult<any>> { (4)
const paths = await fetchContentPathsForAllLocales('\${site}/'); (5)
return {
paths: paths,
fallback: 'blocking',
};
}
1 | Next.js method indicating that we want the page to be rendered statically |
2 | Next.XP method for fetching content from Enonic XP by path |
3 | Next.XP method for creating Next.js response based on results of fetchContent method |
4 | Next.js method to collect paths we want to be static |
5 | Next.XP method for getting paths of all supported contents for every configured locale. ${site} will be substituted with the actual site name. |
As you can see, Next.XP provides methods to create static pages, but the best part is that those methods will also work for server side rendering !
Optional task: Convert to Server Side Rendering (SSR)
Next.js also supports dynamic rendering aka Server Side Rendering (SSR), which may be more useful for certain types of applications/websites.
You may easily convert your front-end into SSR by performing the following changes to the content handler:
-
renaming
getStaticProps
togetServerSideProps
-
setting
isStatic
parameter tofalse
in thecreateResponse
method -
removing the
getStaticPaths
method.
In this mode Next.js will render the page on every request, while still using the same Next.XP methods for fetching data from Enonic XP. More about SSR here.
With prod mode and revalidation sorted out, let’s see how to add multi-language support.