Home >Web Front-end >JS Tutorial >Enhanced Internationalization (i18n) in Next.js 14
Next.js 14 simplifies multilingual website development. This article demonstrates building a multilingual Next.js 14 application, covering key aspects from project setup to a dynamic language switcher.
Key Features:
Building a Multilingual Next.js 14 App:
The process involves these steps:
Project Setup: Create a new Next.js project (e.g., npx create-next-app my-i18n-app
) and install next@latest
and next-intl
. Configure next.config.js
with the next-intl
plugin.
Locale-Specific Content: Create a content
folder with JSON files (e.g., en.json
, es.json
, de.json
) containing translations for each locale. This compensates for Next.js's current lack of automatic translation.
Dynamic Message Loading: Create an i18n.ts
file to dynamically import message JSON files based on the detected locale, ensuring content adapts to user language preferences. Error handling (e.g., notFound
for unsupported locales) is crucial.
Language Routing and Middleware: Implement a middleware.ts
file using next-intl/middleware
to define supported locales, a default locale, and routing rules to direct users to the appropriate language version of the site. The matcher
config ensures that only internationalized paths are processed.
Layout and Page Components: Modify the layout and page components (e.g., app/layout.tsx
, app/page.tsx
) to utilize the useTranslations
hook from next-intl
for accessing translated content. Structure your components to handle different language versions effectively.
Language Switcher Component: Build a LangSwitcher.tsx
component that uses Next.js's router and usePathname
to manage language selection and routing. This component provides a user-friendly interface for switching between languages. Integrate this component into your layout (e.g., app/layout.tsx
).
The complete code examples for each step are available in the original article. This revised response provides a more concise and organized overview, maintaining the key information and image placement.
The above is the detailed content of Enhanced Internationalization (i18n) in Next.js 14. For more information, please follow other related articles on the PHP Chinese website!