Home Web Front-end JS Tutorial Guide to Internationalisation (i) in Next.js with Routing

Guide to Internationalisation (i) in Next.js with Routing

Jul 17, 2024 pm 04:13 PM

Guide to Internationalisation (i) in Next.js with Routing

Internationalisation (i18n) is the process of designing an application to be easily adaptable to different languages and regions without engineering changes. In this article, you will learn how to set up i18n in a Next.js application and create a language switcher to toggle between English and Spanish using next-intl.

Installation

First, you need to install the next-intl library, which facilitates managing internationalisation in Next.js. Run the following command in your terminal:

npm install next-intl

Project Structure

The project structure will be as follows:

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

1. Setting Up Translation Messages

Create a messages directory at the root of your project. Inside this directory, add JSON files for each language you want to support.

messages/en.json

{
  "greeting": "Hello Codú",
  "farewell": "Goodbye Codú"
}

messages/es.json

{
  "greeting": "Hola Codú",
  "farewell": "Adiós Codú"
}

These files contain the translations of the phrases that your application will use.

2. Configuring Next.js

Configure Next.js to support internationalisation in next.config.mjs.

next.config.mjs

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

// List of supported languages
const locales = ['en', 'es'];

export default getRequestConfig(async ({ locale }) => {
  // Validate that the incoming `locale` parameter is valid
  if (!locales.includes(locale)) {
    return { notFound: true };
  }

  return {
    messages: (await import(`./messages/${locale}.json`)).default
  };
});

This file configures Next.js to load the correct translation messages based on the requested language.

3. Internationalisation Middleware

Create middleware to handle redirection and setting the default language.

src/middleware.ts

import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
  // List of all supported languages
  locales: ['en', 'es'],

  // Default language
  defaultLocale: 'en'
});

export const config = {
  // Only match internationalised pathnames
  matcher: ['/', '/(en|es)/:path*']
};

This middleware handles redirecting to the default language if none is specified.

4. Internationalisation Configuration

Create a configuration file to manage internationalisation settings.

src/i18n.ts

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

const locales = ['en', 'es'];

export default getRequestConfig(async ({ locale }) => {
  if (!locales.includes(locale as any)) notFound();

  return {
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

This file validates the locales and loads the corresponding messages.

5. Setting Up Layout and Page

Configure the layout and main page to support internationalisation.

src/app/[locale]/layout.tsx

import { useLocale } from 'next-intl';
import { ReactNode } from 'react';

export default function Layout({ children }: { children: ReactNode }) {
  const locale = useLocale();
  return (
    <html lang={locale}>
      <body>{children}</body>
    </html>
  );
}

src/app/[locale]/page.tsx

import { useTranslations } from 'next-intl';

export default function Page() {
  const t = useTranslations();
  return (
    <div>
      <h1>{t('greeting')}</h1>
      <p>{t('farewell')}</p>
    </div>
  );
}

These files configure the layout and main page to use the translations.

6. Creating the Language Switcher

Finally, create a language switcher to toggle between English and Spanish.

src/app/[locale]/switcher.tsx

'use client';

import { useLocale } from 'next-intl';
import { useRouter } from 'next/navigation';
import { ChangeEvent, useTransition } from 'react';

export default function LocalSwitcher() {
  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  const localActive = useLocale();

  const onSelectChange = (e: ChangeEvent<HTMLSelectElement>) => {
    const nextLocale = e.target.value;
    startTransition(() => {
      router.replace(`/${nextLocale}`);
    });
  };

  return (
    <label className='border-2 rounded'>
      <p className='sr-only'>Change language</p>
      <select
        defaultValue={localActive}
        className='bg-transparent py-2'
        onChange={onSelectChange}
        disabled={isPending}
      >
        <option value='en'>English</option>
        <option value='es'>Spanish</option>
      </select>
    </label>
  );
}

This component allows users to change the interface language.

Conclusion

With these steps, you have successfully set up internationalisation in your Next.js application and created a language switcher to toggle between English and Spanish. This will allow your application to support multiple languages and provide a localised user experience.

The above is the detailed content of Guide to Internationalisation (i) in Next.js with Routing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Aug 05, 2025 am 08:30 AM

This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.

What is the class syntax in JavaScript and how does it relate to prototypes? What is the class syntax in JavaScript and how does it relate to prototypes? Aug 03, 2025 pm 04:11 PM

JavaScript's class syntax is syntactic sugar inherited by prototypes. 1. The class defined by class is essentially a function and methods are added to the prototype; 2. The instances look up methods through the prototype chain; 3. The static method belongs to the class itself; 4. Extends inherits through the prototype chain, and the underlying layer still uses the prototype mechanism. Class has not changed the essence of JavaScript prototype inheritance.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Aug 03, 2025 am 05:54 AM

JavaScript's array methods map, filter and reduce are used to write clear and functional code. 1. Map is used to convert each element in the array and return a new array, such as converting Celsius to Fahrenheit; 2. Filter is used to filter elements according to conditions and return a new array that meets the conditions, such as obtaining even numbers or active users; 3. Reduce is used to accumulate results, such as summing or counting frequency, and the initial value needs to be provided and returned to the accumulator; none of the three modify the original array, and can be called in chain, suitable for data processing and conversion, improving code readability and functionality.

How can you remove a CSS class from a DOM element using JavaScript? How can you remove a CSS class from a DOM element using JavaScript? Aug 05, 2025 pm 12:51 PM

The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList

Vercel SPA routing and resource loading: Solve deep URL access issues Vercel SPA routing and resource loading: Solve deep URL access issues Aug 13, 2025 am 10:18 AM

This article aims to solve the problem of deep URL refresh or direct access causing page resource loading failure when deploying single page applications (SPAs) on Vercel. The core is to understand the difference between Vercel's routing rewriting mechanism and browser parsing relative paths. By configuring vercel.json to redirect all paths to index.html, and correct the reference method of static resources in HTML, change the relative path to absolute path, ensuring that the application can correctly load all resources under any URL.

Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Aug 13, 2025 pm 01:03 PM

This tutorial aims to solve the problem of loading assets (CSS, JS, images, etc.) when accessing multi-level URLs (such as /projects/home) when deploying single page applications (SPAs) on Vercel. The core lies in understanding the difference between Vercel's routing rewriting mechanism and relative/absolute paths in HTML. By correctly configuring vercel.json, ensure that all non-file requests are redirected to index.html and correcting asset references in HTML as absolute paths, thereby achieving stable operation of SPA at any depth URL.

JavaScript Performance Optimization: Beyond the Basics JavaScript Performance Optimization: Beyond the Basics Aug 03, 2025 pm 04:17 PM

OptimizeobjectshapesbyinitializingpropertiesconsistentlytomaintainhiddenclassesinJavaScriptengines.2.Reducegarbagecollectionpressurebyreusingobjects,avoidinginlineobjectcreation,andusingtypedarrays.3.Breaklongtaskswithasyncscheduling,usepassiveeventl

See all articles