0
0
NextJSframework~5 mins

Sub-path routing for locales in NextJS

Choose your learning style9 modes available
Introduction

Sub-path routing for locales helps show your website in different languages by using parts of the URL. It makes it easy for visitors to see content in their language.

You want to support multiple languages on your website.
You want URLs like /en/about or /fr/about to show content in English or French.
You want search engines to understand your site has different language versions.
You want to keep your site organized by language using URL paths.
You want users to switch languages by changing the URL path.
Syntax
NextJS
export const nextConfig = {
  i18n: {
    locales: ['en', 'fr', 'es'],
    defaultLocale: 'en',
    localeDetection: true
  }
};

The locales array lists all supported languages.

The defaultLocale is the language shown when no locale is specified.

Examples
This config supports English and French. English is the default language.
NextJS
i18n: {
  locales: ['en', 'fr'],
  defaultLocale: 'en'
}
This config supports English, French, and German. French is the default language.
NextJS
i18n: {
  locales: ['en', 'fr', 'de'],
  defaultLocale: 'fr'
}
Sample Program

This Next.js component shows the current language and available languages using sub-path routing. The config sets English, French, and Spanish as supported languages with English as default.

NextJS
import { useRouter } from 'next/router';

export default function Home() {
  const { locale, locales, defaultLocale, asPath } = useRouter();

  return (
    <main>
      <h1>Welcome!</h1>
      <p>Current language: {locale}</p>
      <p>Default language: {defaultLocale}</p>
      <p>Available languages: {locales.join(', ')}</p>
      <p>Current path: {asPath}</p>
    </main>
  );
}

// next.config.js
const nextConfig = {
  i18n: {
    locales: ['en', 'fr', 'es'],
    defaultLocale: 'en'
  }
};

export default nextConfig;
OutputSuccess
Important Notes

When you visit /fr, the page shows French content automatically.

Make sure to add translations for each locale in your app.

Locale detection can be turned on or off to control automatic language selection.

Summary

Sub-path routing uses URL parts like /en or /fr to show different languages.

Configure supported languages in next.config.js under i18n.

Use Next.js router to get current locale and show language-specific content.