Step 11 of 21 (52% complete)

Generate Static Params during build

Step Code

The code for this specific step can be found on the following branch:

Click on a link to view the code for this step on GitHub.

Next.js provides a powerful feature called generateStaticParams that optimizes your application by pre-rendering pages at build time. When implemented in the root layout, it offers significant benefits for localized applications.

What is generateStaticParams?

The generateStaticParams function allows you to define which dynamic route segments should be pre-rendered at build time. For localization, this means you can pre-generate pages for all supported languages, improving performance and user experience.

Implementation in Root Layout

// app/[locale]]/layout.tsx
import { LOCALES } from '@/lib/optimizely/utils/language';

export function generateStaticParams() {
  try {
    return LOCALES.map((locale) => ({ locale }));
  } catch (e) {
    console.error(e);
    return [];
  }
}

// ... rest of the layout component

How Root Layout Static Parameters Work

When you implement generateStaticParams in the root layout:

  1. Automatic Propagation: Next.js automatically applies these parameters to all child pages, eliminating the need to repeat this function in every page file.
  2. Build-Time Generation: During next build, Next.js generates static HTML files for each locale defined in your LOCALES array.
  3. Efficient Rendering: Child pages inherit the locale parameter, ensuring consistent localization throughout your application.
  4. Optimized Performance: Static generation significantly reduces server load and improves page load times.

Generating Static Params For Dynamic Pages

For dynamic pages, you can generate static parameters based on content from your CMS:

// app/[locale]/[slug]/page.tsx
import {
  getValidLocale,
  mapPathWithoutLocale,
} from '@/lib/optimizely/utils/language'

export async function generateStaticParams() {
  try {
    const pageTypes = ['CMSPage']
    const pathsResp = await optimizely.AllPages({ pageType: pageTypes })
    const paths = pathsResp.data?._Content?.items ?? []
    const filterPaths = paths.filter(
      (path) => path && path._metadata?.url?.default !== null
    )
    const uniquePaths = new Set<string>()
    filterPaths.forEach((path) => {
      const cleanPath = mapPathWithoutLocale(
        path?._metadata?.url?.default ?? ''
      )
      uniquePaths.add(cleanPath)
    })

    return Array.from(uniquePaths).map((slug) => ({
      slug,
    }))
  } catch (e) {
    console.error(e)
    return []
  }
}
# lib/optimizely/queries/AllPages.graphql

query AllPages($pageType: [String]) {
  _Content(where: { _metadata: { types: { in: $pageType } } }) {
    items {
      _metadata {
        displayName
        url {
          base
          internal
          hierarchical
          default
          type
        }
        types
        status
      }
    }
  }
}

Performance Benefits

Implementing generateStaticParams provides several performance advantages:

  1. Reduced Time to First Byte (TTFB): Pre-rendered pages are served instantly from the CDN.
  2. Improved Core Web Vitals: Static pages typically have better Largest Contentful Paint (LCP) and First Input Delay (FID) scores.
  3. Lower Server Costs: With reduced server-side rendering, you can often lower your hosting costs, especially for high-traffic sites.
  4. Consistent Performance Across Locales: All language versions of your site benefit from the same optimizations.
  5. SEO Advantages: Search engines can more easily index your content in all languages.

Implementation Considerations

While static generation offers many benefits, consider these factors:

  1. Build Time: Pre-rendering many locales and pages can increase build time. Monitor this as your site grows.
  2. Content Freshness: For frequently updated content, combine static generation with revalidation strategies.
  3. Storage Requirements: More pre-rendered pages require more storage on your hosting provider.

Have questions? I'm here to help!

Contact Me