Blog>
Snippets

Static Generation with getStaticProps for Multiple Locales

Illustrate how to use getStaticProps in Next.js 14 to generate static pages for each locale, including translating page content based on the locale.
export async function getStaticProps({ locale }) {
  // Fetch necessary data to render the page with `locale`
  const messages = await fetchTranslationsForLocale(locale);
  return {
    props: {
      // Pass the messages to the page component as a prop
      messages,
    },
  };
}
This snippet defines a getStaticProps function that fetches locale-specific data and passes it as props to the page component in a Next.js application. The fetchTranslationsForLocale function is a placeholder for the actual data-fetching logic and should be implemented to retrieve the translations based on the given locale.
export async function getStaticPaths() {
  // Define all the locales you support
  const locales = ['en', 'es', 'fr'];
  // Generate paths for each locale
  const paths = locales.map((locale) => ({
    params: { ... },
    locale,
  }));
  return {
    paths,
    fallback: false,
  };
}
This snippet includes a getStaticPaths function that generates paths for each supported locale. Next.js will statically pre-render pages for each path/locale combination. The ... in params should be replaced with actual parameter values required by the page.
import React from 'react';

export default function HomePage({ messages }) {
  return (
    <div>
      {/* Render your page using the messages prop for locale-specific content */}
      <h1>{messages.welcome}</h1>
      {/* Other page components */}
    </div>
  );
}
This is the React component for the home page. It receives messages as a prop, which contains the locale-specific translations. This component uses the messages prop to display translated content.
export const config = { locales: ['en', 'es', 'fr'], defaultLocale: 'en' };
This configuration snippet, typically placed in next.config.js, is needed to define the locales supported by the Next.js application and the default locale.
body {
  font-family: 'Arial', sans-serif;
}
h1 {
  color: #333;
}
A simple CSS snippet to style the body text and h1 heading of the page. You can replace or extend these styles as needed for your application.