Next.js 14 Static Site Localization Tutorial

published on 01 May 2024

Next.js 14 simplifies building multilingual static websites with features like automatic locale detection, language routing, and static site generation. This tutorial covers:

  • Setting up a Next.js 14 project with internationalization (i18n) support
  • Creating translation files and managing locale state
  • Fetching translations and generating static routes
  • Implementing a language switcher component
  • Displaying content based on the user's locale

To enhance performance, you'll learn how to preload translations using getStaticProps. The tutorial also explores techniques for crafting an engaging multilingual experience, such as using useState to manage locale state and displaying content based on the user's locale.

Key Takeaway Description
Project Setup Configure a Next.js 14 project with i18n support using the next-intl plugin.
Translation Files Create translation files for each locale in a locales folder.
Static Routes Use getMessages and generateStaticParams to fetch translations and generate static routes.
Language Switcher Implement a LocaleSwitcher component to allow users to switch between languages.
Preloaded Translations Leverage getStaticProps to preload translations for improved performance.
Locale State Management Utilize useState to manage and update the locale state.
Content Display Display content based on the user's locale using state management hooks.

By following this tutorial, you'll learn how to build a multilingual static site with Next.js 14, providing a seamless and efficient experience for your global audience.

Setting Up Your Next.js 14 Project

Next.js 14

Project Setup and Configuration

To set up a new Next.js 14 project, follow these steps:

Step 1. Create a fresh Next.js project

Run the command below to create a new Next.js project. For this example, we'll name it i18n-next-app:

npx create-next-app i18n-next-app

Step 2. Install required packages

Navigate into your project folder and install Next.js (Version 14) and the next-intl package:

cd i18n-next-app
npm install next@latest next-intl

Step 3. Configure i18n support

Enable i18n support in Next.js 14 by adding the following configuration in your next.config.js:

const withNextIntl = require('next-intl/plugin')();
module.exports = withNextIntl({
  // include other configs here
});

This code configures Next.js with the next-intl plugin for enhanced internationalization capabilities.

Creating Basic Site Structure

Let's create a basic site structure with a header, home page, and about page.

Create a Header component

Create a components folder and a Header component:

// components/Header.tsx
import Link from "next/link";

export default function Header() {
  return (
    <header className="bg-gray-200 shadow">
      <nav className="container flex px-2 py-2 gap-5">
        <Link href="/">Home</Link>
        <Link href="/about">About</Link>
      </nav>
    </header>
  );
}

Create pages

Update the homepage with 'Hello World':

// pages/index.tsx
export default function Home() {
  return (
    <div>
      Hello World!
    </div>
  );
}

Create the about page:

// pages/about.tsx
export default function AboutPage() {
  return (
    <div>
      This application is a fully translated static website
    </div>
  );
}

These steps set up a basic Next.js 14 project with a header, home page, and about page, ready for localization.

Internationalizing Your Next.js Project

Next.js

Using next-intl for Localization

To make our Next.js project multilingual, we'll use the next-intl library. This library provides a simple way to manage translations.

First, let's install next-intl by running the following command in our project directory:

npm install next-intl

Next, we'll configure next-intl in our next.config.js file by adding the following code:

const withNextIntl = require('next-intl/plugin')();
module.exports = withNextIntl({
  // include other configs here
});

This code enables next-intl support in our Next.js project.

Creating Translation Files

To create translation files, we'll create a locales folder in the root of our project and add separate folders for each locale we want to support (e.g., en, es, fr). Inside each locale folder, we'll create a messages.json file that contains the translated content for that locale.

Here's an example of what our locales/en/messages.json file might look like:

Key Value
hello Hello
about About

And here's an example of what our locales/es/messages.json file might look like:

Key Value
hello Hola
about Acerca de

Fetching Translations and Generating Static Routes

To fetch translations and generate static routes, we'll use the getMessages function from next-intl to load the translated content for each locale. We'll also use the generateStaticParams function to generate static routes for each locale.

Here's an example of how we might use these functions in our pages/_app.tsx file:

import { getMessages, generateStaticParams } from 'next-intl';

export async function getStaticProps({ locale }) {
  const messages = await getMessages(locale, 'messages');
  const staticParams = await generateStaticParams({
    locales: ['en', 'es', 'fr'],
    defaultLocale: 'en',
  });

  return {
    props: {
      messages,
      staticParams,
    },
  };
}

This code fetches the translated content for the current locale and generates static routes for each locale.

By following these steps, we've successfully internationalized our Next.js project using next-intl.

Building a Language Switcher Component

To allow users to switch between languages on your static Next.js site, you'll need to create a language switcher component. This component will display the available language options and handle the logic for updating the site's locale when a new language is selected.

Implementing Language Toggle

One way to implement a language switcher is by creating a LocaleSwitcher component that renders a dropdown or list of available languages. Here's an example of how you could structure this component:

import { useRouter } from 'next/router';
import Link from 'next/link';

const LocaleSwitcher = () => {
  const router = useRouter();
  const { locales, locale: activeLocale } = router;

  const changeLocale = (newLocale) => {
    router.push(router.route, router.asPath, { locale: newLocale });
  };

  return (
    <div>
      <p>Current Language: {activeLocale}</p>
      <select value={activeLocale} onChange={(e) => changeLocale(e.target.value)}>
        {locales.map((locale) => (
          <option key={locale} value={locale}>
            {locale.toUpperCase()}
          </option>
        ))}
      </select>
    </div>
  );
};

export default LocaleSwitcher;

In this example, the LocaleSwitcher component uses the useRouter hook from Next.js to access the available locales and the currently active locale. It renders a <select> element with options for each available locale, using the locales array provided by the router.

When a user selects a new language from the dropdown, the changeLocale function is called, which uses the router.push method to update the URL with the new locale. This will trigger a re-render of the page with the content for the selected language.

Integrating the Language Switcher

To integrate the LocaleSwitcher component into your site, you can add it to your layout or header component. For example:

import LocaleSwitcher from './LocaleSwitcher';

const Header = () => {
  return (
    <header>
      <nav>
        {/* Navigation links */}
      </nav>
      <LocaleSwitcher />
    </header>
  );
};

export default Header;

With this setup, users can easily switch between languages by selecting their preferred option from the language switcher dropdown in the header.

sbb-itb-5683811

Preloading Translations with getStaticProps

When building a multilingual static site with Next.js 14, preloading translations is crucial for providing a seamless user experience. One effective approach to achieve this is by leveraging the getStaticProps function. In this section, we'll explore how to utilize getStaticProps to preload translations, resulting in faster page loads and an improved user experience.

Improving Performance with Preloaded Translations

Preloading translations using getStaticProps can significantly enhance the performance of your multilingual site. This approach ensures that all translations are available at build time, eliminating the need for runtime data fetching. As a result, your users can instantly access page content in their preferred language.

Here's an example of how you can preload translations using getStaticProps:

export async function getStaticProps() {
  const translations = {
    en: {
      greeting: "Hello",
      content: "This is a simple content page supporting English and Spanish.",
      switch: "Switch to Spanish",
    },
    es: {
      greeting: "Hola",
      content: "Esta es una página de contenido simple que admite inglés y español.",
      switch: "Cambiar a inglés",
    },
  };

  return {
    props: {
      allTranslations: translations, // Pass all translations to the page
    },
  };
}

In this example, we define a getStaticProps function that returns an object containing all translations for the page. By passing these translations as props to the page, we can ensure that they're available at build time, resulting in faster page loads.

By leveraging getStaticProps to preload translations, you can create a multilingual static site that provides a seamless and efficient user experience. In the next section, we'll explore how to display content based on the user's locale.

Displaying Content Based on Locale

When building a multilingual static site with Next.js 14, it's crucial to display content based on the user's locale. This involves accessing and displaying translated content according to the current user locale using state management hooks.

Managing Locale State with useState

To track and update the locale state, you can use the useState hook. This hook allows you to add React state to function components.

Here's an example of how you can use useState to manage the locale state:

import { useState } from 'react';

function LocaleSwitcher() {
  const [locale, setLocale] = useState('en'); // Initialize locale state to 'en'

  const handleLocaleChange = (newLocale) => {
    setLocale(newLocale); // Update locale state on language switch
  };

  return (
    <div>
      <p>Current locale: {locale}</p>
      <button onClick={() => handleLocaleChange('es')}>Switch to Spanish</button>
      <button onClick={() => handleLocaleChange('en')}>Switch to English</button>
    </div>
  );
}

In this example, we initialize the locale state to 'en' using useState. We then define a handleLocaleChange function that updates the locale state when the user switches languages. Finally, we use the locale state to display the current locale and update the content accordingly.

By leveraging useState to manage the locale state, you can create a seamless and efficient multilingual experience for your users.

Conclusion: Localizing Static Sites with Next.js 14

Key Takeaways from the Tutorial

In this tutorial, we've covered the essential steps to build a multilingual static site using Next.js 14. We've explored the benefits of using Next.js 14 for static site localization, including improved performance and seamless language switching. We've also learned how to set up a Next.js 14 project, create translation files, fetch translations, and generate static routes.

Here's a summary of what we've learned:

  • Set up a Next.js 14 project with internationalization support
  • Create translation files and manage locale state
  • Fetch translations and generate static routes
  • Implement a language switcher component
  • Display content based on the user's locale

Next Steps and Improvements

While this tutorial has provided a solid foundation for building a multilingual static site with Next.js 14, there are still opportunities for further learning and improvement. Some potential areas to explore include:

Area Description
Advanced internationalization techniques Explore Next.js 14's internationalization features in more depth
Performance optimization Investigate ways to further optimize the performance of your multilingual site
Accessibility and SEO considerations Learn how to ensure your multilingual site is accessible and optimized for search engines
Integrating with other tools and services Explore how to integrate your multilingual site with other tools and services

By continuing to learn and improve, you can create a truly exceptional multilingual experience for your users.

FAQs

How to localize a Next.js app?

To localize a Next.js app, you can set a NEXT_LOCALE=the-locale cookie. This cookie takes priority over the accept-language header. You can set this cookie using a language switcher. When a user returns to the site, it will use the locale specified in the cookie when redirecting from / to the correct locale location.

Is Next.js 14 multilingual?

Yes, Next.js 14 simplifies multilingual web development. It provides tools like language routing and dynamic message loading to help developers create dynamic, multilingual web apps.

Related posts

Read more

Make your website with
Unicorn Platform Badge icon