Static Site Generation

Contents

In this chapter you will learn about the static site generation capabilities of Next.js, and how Enonic triggers regeneration of pages when content is published.

Introduction

Your Next.js front-end uses Static Site Generation (SSG) when possible. This gives you fast pages, but adds a build step.

For more information visit the Next.js rendering 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 this case, pages get pre-rendered statically before the server starts.

  1. Stop the dev server - Stop your existing Next.js dev instance before you continue.

  2. Start Next.js in prod mode:

    npm run prod

    This takes longer than starting dev mode, since the application is built first.

  3. Verify the result - Point your incognito window to http://localhost:3000. You should see the published items, like in dev mode. Only this time, they load much faster.

Since prod mode runs on the default port 3000 (same as dev mode), Content Studio preview continues to work without any configuration changes. The draft cookie issued by the dev server belongs to another build, so the proxy sends the first preview request through /api/preview again and draft mode is re-enabled for the prod build.

Task: Test page invalidation

With all pages now being cached as files, Next.js must be instructed to regenerate the pages when a change is published.

  1. Check the site - Verify that the Next.XP app is added to your site, and that the site is published. You added the app in the Preview chapter, and published the site in the Pages chapter. This ensures that the revalidation hook is triggered when you publish content.

  2. Edit your front page, and publish the changes - This triggers a revalidation hook, which is built into the Next.XP app.

  3. Verify the update - The page at http://localhost:3000 is updated 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 in the site it is added to. The /api/revalidate route resolves the locale from the publishing project, so a specific path is revalidated as its locale-prefixed page; without a path everything is revalidated.

The Next.js log also shows that the revalidation was triggered.

A look at the code

Static Site Generation is controlled within the content page handler.

The most interesting function is:

  • generateStaticParams() - Next.js uses this function at build time to create a list of pages to compile before the server starts.

Here is the full page handler:

src/app/[locale]/[[…​contentPath]]/page.tsx
import { FetchContentResult, validateData } from '@enonic/nextjs-adapter';
import { fetchContent, fetchContentPathsForAllLocales } from '@enonic/nextjs-adapter/server';
import MainView from '@enonic/nextjs-adapter/views/MainView';

import '../../../components/_mappings';
import { Metadata } from 'next';
import { draftMode } from 'next/headers';
import React from 'react';
import PageEditorScript from '../../../components/views/PageEditorScript';

// NB. Using this option with default value bails out static generation !!!
// export const dynamic = 'auto'

// The revalidate option is only available when using the Node.js Runtime.
// This means using the revalidate option with runtime = 'edge' will not work.
export const revalidate = 3600

// PageProps type matches the Next.js route [[...contentPath]]
// where contentPath is optional (can be undefined for root paths)
export type PageProps = {
    locale: string,
    contentPath?: string[],
}

export default async function Page({params}: { params: Promise<PageProps> }) {
    const {isEnabled: draft} = await draftMode();
    const resolvedParams = await params;

    const data: FetchContentResult = await fetchContent({
        ...resolvedParams,
        contentPath: resolvedParams.contentPath || []
    });

    validateData(data);

    console.debug(`Rendered ${draft ? 'draft ' : ''}page at '/${data.meta.locale}/${data.meta.path}'`);

    return (
        <>
            <MainView {...data}/>
            <PageEditorScript meta={data.meta}/>
        </>
    )
};

export async function generateMetadata({params}: { params: Promise<PageProps> }): Promise<Metadata> {
    const resolvedParams = await params;
    const {common} = await fetchContent({
        ...resolvedParams,
        contentPath: resolvedParams.contentPath || []
    });
    return {
        title: common?.get?.displayName || 'Not found',
    };
}

export async function generateStaticParams(props: { params: PageProps }): Promise<any[]> {
    return await fetchContentPathsForAllLocales();
}

As you can see, Next.XP provides methods to create static pages, and Next.js chooses the rendering and caching scheme based on what your code is doing.

Summary

You’ve run the front-end in prod mode with statically generated pages, and seen the Next.XP app revalidate them when content is published.

Next, you’ll add multi-language support.


Contents

Contents