avatarDimitar Atanasov

Summary

The provided content is a comprehensive guide on implementing internationalization (i18n) in a Next.js application using the App Router and next-intl library.

Abstract

The guide outlines a step-by-step process for setting up a multilingual Next.js application, starting with the installation of Node.js and the creation of a new Next.js project. It details the integration of the next-intl library for handling localized messages and date/time formatting. The article also covers the structuring of project files to support multiple languages, including the creation of JSON files for each locale's messages and the configuration of Next.js and next-intl. Middleware for locale detection and routing is discussed, along with the utilization of localized content in components using the useTranslations hook. The guide emphasizes the importance of internationalization for global reach and user experience, suggesting further steps such as adding more locales, formatting dates and numbers, and implementing advanced routing strategies.

Opinions

  • The author believes that internationalization involves more than just text translation; it requires a comprehensive approach to cater to a global audience.
  • The use of Next.js with its App Router, in conjunction with next-intl, is presented as a robust solution for building multilingual applications.
  • Organizing project files with a clear structure, including localization resources and configuration files, is considered essential for effective internationalization.
  • The guide suggests that validating supported locales and loading corresponding messages are crucial steps in the configuration process.
  • Implementing middleware for locale detection and routing is highlighted as an important aspect of internationalization, ensuring that the application can automatically adapt to the user's locale.
  • The author encourages continuous adaptation and refinement of internationalization strategies to meet the needs of a diverse, global audience.

Internationalization in Next.js with the App Router and next-intl. A step-by-step guide.

Creating web applications that cater to a global audience requires more than just translating text; it demands a comprehensive approach to internationalization (i18n). Next.js, with its cutting-edge App Router, coupled with next-intl, provides a robust foundation for building multilingual applications. This guide offers a step-by-step walkthrough on setting up internationalization in your Next.js project, ensuring your application is accessible and user-friendly for a worldwide audience.

Prerequisites

Before diving in, ensure you have Node.js installed on your system and are familiar with the basics of React and Next.js.

Step 1: Setting Up Your Next.js Project

Begin by creating a new Next.js project if you haven’t done so already:

npx create-next-app@latest my-next-global-app
cd my-next-global-app

This command scaffolds a new Next.js application in the directory my-next-global-app.

Step 2: Integrating next-intl

next-intl is a library that facilitates internationalization in Next.js projects, offering features like localized messages and date/time formatting.

Install next-intl by running:

npm install next-intl

Step 3: Structuring Your Project for Internationalization

For effective internationalization, organize your project files to include localization resources and configuration files. Here’s the recommended structure:

my-next-global-app
├── messages
│   ├── en.json
│   ├── fr.json
│   └── ...
├── next.config.mjs
└── src
    ├── i18n.ts
    ├── middleware.ts
    └── app
        └── [locale]
            ├── layout.tsx
            └── page.tsx

Localization Messages

Create JSON files within the messages directory for each locale you plan to support (e.g., en.json for English, fr.json for French). These files will contain the localized strings for your application.

Example en.json:

{
  "greeting": "Hello, world!"
}

Example fr.json:

{
  "greeting": "Bonjour, le monde!"
}

Step 4: Configuring next-intl and Next.js

'next.config.mjs'

Configure Next.js to use next-intl for internationalization support:

import createNextIntlPlugin from 'next-intl/plugin';

const withNextIntl = createNextIntlPlugin();

export default withNextIntl({
  // Your existing Next.js configuration here
});

'src/i18n.ts'

Set up a function to provide localization configurations based on the user’s locale. This involves loading the corresponding messages from the messages directory.

import { notFound } from 'next/navigation';
import { getRequestConfig } from 'next-intl/server';

const locales = ['en', 'fr']; // Define supported locales

export default getRequestConfig(async ({ locale }) => {
  if (!locales.includes(locale)) notFound(); // Validate locale
  
  return {
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

'src/middleware.ts'

Implement middleware to handle locale detection and routing, specifying the supported locales and default locale:

import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
  locales: ['en', 'fr'],
  defaultLocale: 'en',
});

export const config = {
  matcher: ['/', '/(en|fr)/:path*'],
};

Step 5: Utilizing Localized Content in Your Application

With the internationalization infrastructure in place, you can now use localized strings within your Next.js components.

Example Usage in a Page Component

In app/[locale]/page.tsx, utilize the useTranslations hook from next-intl to access and render localized content:

import { useTranslations } from 'next-intl';

export default function HomePage() {
  const t = useTranslations();
  
  return <h1>{t('greeting')}</h1>; // Dynamically renders "Hello, world!" or "Bonjour, le monde!"
}

Next Steps

Following this setup, your Next.js application is now equipped to serve content in multiple languages, adapting to the user’s locale. From here, you can expand your internationalization efforts by:

  • Adding more locales and translations.
  • Exploring date and number formatting with next-intl.
  • Implementing advanced routing strategies to cater to different regional content and SEO requirements.

Conclusion

Embracing internationalization is a significant step towards making your Next.js application truly global. By following this guide, you’ve laid down a solid foundation for serving a multilingual user base, enhancing the accessibility and user experience of your application. As you expand your application’s global reach, remember to continuously adapt and refine your internationalization strategies to meet the diverse needs of your global audience.

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

Nextjs
React
JavaScript
Programming
Web Development
Recommended from ReadMedium