0
0
NextJSframework~15 mins

Sub-path routing for locales in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - Sub-path routing for locales
What is it?
Sub-path routing for locales means organizing your website URLs so that each language version has its own path segment, like '/en' for English or '/fr' for French. This helps visitors and search engines know which language content to show based on the URL. Instead of switching languages with query parameters or cookies, the language is part of the URL path itself.
Why it matters
Without sub-path routing for locales, users might get confused about which language they are viewing, and search engines may not index the different language versions properly. This can hurt user experience and SEO. Sub-path routing makes language clear and consistent, improving accessibility and helping websites reach a global audience effectively.
Where it fits
Before learning this, you should understand basic Next.js routing and how internationalization (i18n) works in web apps. After mastering sub-path routing, you can explore advanced localization techniques like dynamic content translation, language detection, and server-side rendering for multiple locales.
Mental Model
Core Idea
Sub-path routing for locales means putting the language code as the first part of the URL path to clearly separate content by language.
Think of it like...
It's like having different doors labeled with language names at the entrance of a building, so visitors know exactly which door to enter for their preferred language.
┌─────────────┐
│ Website URL │
└─────┬───────┘
      │
      ▼
┌───────────────┐
│ /en/about     │ ← English content
│ /fr/about     │ ← French content
│ /es/about     │ ← Spanish content
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Basic Next.js Routing
🤔
Concept: Learn how Next.js maps URL paths to pages in the 'pages' folder.
In Next.js, each file inside the 'pages' folder corresponds to a route. For example, 'pages/about.js' is served at '/about'. This simple mapping lets you create pages by adding files.
Result
Visiting '/about' shows the content from 'pages/about.js'.
Knowing this basic routing is essential because sub-path routing builds on how Next.js handles URLs.
2
FoundationWhat is Locale and Internationalization?
🤔
Concept: Locale means the language and region settings that determine content language and formatting.
Internationalization (i18n) is preparing your app to support multiple languages. A locale like 'en-US' means English for the US region. Next.js supports i18n by letting you define which locales your app supports.
Result
Your app can serve content in different languages based on locale settings.
Understanding locales helps you see why URLs need to reflect language choices clearly.
3
IntermediateConfiguring Next.js for Sub-path Locales
🤔Before reading on: Do you think Next.js automatically adds language codes to URLs, or do you need to configure it? Commit to your answer.
Concept: Next.js requires configuration to enable sub-path routing for locales using the i18n field in next.config.js.
You add an 'i18n' object in next.config.js with 'locales' (like ['en', 'fr']) and a 'defaultLocale' (like 'en'). This tells Next.js to prefix URLs with the locale code, e.g., '/fr/about'.
Result
URLs automatically include the locale as the first path segment, enabling sub-path routing.
Knowing that Next.js needs explicit config prevents confusion about why URLs don't change language by default.
4
IntermediateCreating Locale-Specific Content Pages
🤔Before reading on: Do you think you need separate files for each language, or can one file handle all locales? Commit to your answer.
Concept: You can use one page file with translation data to serve multiple locales, or create separate files/folders for each locale.
Using libraries like next-translate or next-i18next, you load translation JSON files per locale and use hooks to display the right text. Alternatively, you can organize pages in folders like 'pages/en/about.js' and 'pages/fr/about.js'.
Result
The same URL path shows content in the correct language based on the locale prefix.
Understanding content organization options helps you choose the best approach for your project size and complexity.
5
IntermediateHandling Navigation with Locale Paths
🤔Before reading on: When linking between pages, do you think you must include the locale in the link URL manually? Commit to your answer.
Concept: Next.js Link component and router handle locale-aware navigation automatically when configured properly.
When you use , Next.js prepends the current locale path like '/fr/about'. You can also change locale programmatically with router.push and locale option.
Result
Users navigate between pages without losing their language choice, and URLs stay consistent.
Knowing automatic locale handling in navigation prevents broken links and language mix-ups.
6
AdvancedSEO Benefits and Challenges of Sub-path Routing
🤔Before reading on: Do you think sub-path routing improves SEO for multilingual sites or causes duplicate content issues? Commit to your answer.
Concept: Sub-path routing helps search engines index each language version separately, improving SEO, but requires proper hreflang tags and sitemap setup.
You add hreflang tags in your pages' head to tell search engines about language versions. Also, generate sitemaps listing all locale URLs. Without this, search engines might treat pages as duplicates or rank them poorly.
Result
Search engines understand your multilingual site structure, improving visibility and user targeting.
Understanding SEO implications ensures your localization efforts bring real traffic benefits.
7
ExpertCustom Server and Middleware for Locale Detection
🤔Before reading on: Do you think Next.js automatically detects user language and redirects to the right locale path, or do you need custom logic? Commit to your answer.
Concept: You can use Next.js middleware or custom server logic to detect user language from headers or cookies and redirect to the correct locale sub-path.
Middleware runs before rendering and can check Accept-Language headers. If a user visits '/', middleware redirects to '/en' or '/fr' based on preference. This improves user experience by landing them on their language version automatically.
Result
Users see the right language version URL without manual selection, improving engagement.
Knowing how to implement middleware for locale detection unlocks advanced user-friendly localization.
Under the Hood
Next.js uses the i18n configuration in next.config.js to automatically prefix routes with locale codes. Internally, it rewrites URLs and matches them to pages while passing locale info to components. The Link component and router use this locale context to generate correct URLs. Middleware can intercept requests to detect and redirect based on language preferences.
Why designed this way?
Sub-path routing was chosen because it creates clear, SEO-friendly URLs that are easy to share and bookmark. Alternatives like query parameters or cookies are less visible and less reliable for search engines. Next.js integrates this routing pattern to simplify multilingual site development while allowing customization via middleware.
┌───────────────┐
│ User requests │
│   /fr/about   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next.js Router│
│ detects 'fr'  │
│ as locale     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Loads page    │
│ with 'fr'     │
│ translations  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Next.js automatically add locale prefixes to URLs without config? Commit yes or no.
Common Belief:Next.js automatically adds language codes to URLs when you add multiple locales.
Tap to reveal reality
Reality:You must explicitly configure the i18n field in next.config.js to enable sub-path routing for locales.
Why it matters:Without this config, URLs won't show language prefixes, causing confusion and broken localization.
Quick: Do you think sub-path routing means you must duplicate all pages for each language? Commit yes or no.
Common Belief:You need separate page files for each language to support sub-path routing.
Tap to reveal reality
Reality:You can use one page file with translation data loaded dynamically, avoiding duplication.
Why it matters:Believing you must duplicate pages leads to unnecessary code bloat and maintenance overhead.
Quick: Does sub-path routing alone guarantee good SEO for multilingual sites? Commit yes or no.
Common Belief:Just having language codes in URLs is enough for SEO to work well.
Tap to reveal reality
Reality:You also need hreflang tags and proper sitemap setup to avoid duplicate content penalties and improve indexing.
Why it matters:Ignoring SEO best practices can cause poor search rankings despite correct URL structure.
Quick: Can middleware always detect user language perfectly and redirect correctly? Commit yes or no.
Common Belief:Middleware can always detect user language and redirect flawlessly to the right locale path.
Tap to reveal reality
Reality:Language detection is heuristic and can fail due to ambiguous headers or user preferences; fallback strategies are needed.
Why it matters:Overreliance on detection can frustrate users if they get redirected incorrectly.
Expert Zone
1
Next.js locale sub-path routing integrates deeply with its routing system, so custom dynamic routes must carefully handle locale prefixes to avoid conflicts.
2
Middleware for locale detection should be lightweight and fast to avoid slowing down page loads, requiring careful optimization.
3
When using static site generation, you must generate pages for all locale paths to avoid 404 errors, which can be tricky with many languages.
When NOT to use
Sub-path routing is not ideal if you want language-neutral URLs or prefer language selection via cookies or user profiles. Alternatives include domain-based routing (different domains per language) or query parameter-based localization, which may suit some projects better.
Production Patterns
In production, teams often combine sub-path routing with middleware for automatic locale detection, use translation libraries for content, and implement SEO best practices like hreflang tags and localized sitemaps. They also monitor analytics per locale to optimize user experience.
Connections
REST API Versioning
Both use URL path segments to distinguish versions or locales.
Understanding sub-path routing helps grasp how APIs use URL paths to serve different versions, showing a common pattern of clear URL-based differentiation.
International Postal Addressing
Both organize information hierarchically to route correctly based on region or language.
Knowing how postal addresses use country and region codes helps understand why URLs use locale prefixes to direct users to the right content.
Human Language Dialects
Locales reflect language and region variations, similar to dialects in linguistics.
Recognizing locale sub-paths as dialect markers helps appreciate the need for precise content targeting in global communication.
Common Pitfalls
#1Forgetting to configure i18n in next.config.js causes no locale prefixes in URLs.
Wrong approach:module.exports = { // no i18n field here };
Correct approach:module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en' } };
Root cause:Assuming Next.js enables locale routing automatically without explicit config.
#2Hardcoding links without locale causes navigation to wrong language pages.
Wrong approach:About // no locale awareness
Correct approach:About
Root cause:Not using Next.js Link component's locale-aware features leads to broken language navigation.
#3Not adding hreflang tags leads to SEO penalties for duplicate content.
Wrong approach: About
Correct approach: About
Root cause:Ignoring SEO best practices for multilingual sites.
Key Takeaways
Sub-path routing for locales means adding the language code as the first part of the URL path to clearly separate language versions.
Next.js requires explicit i18n configuration to enable locale sub-path routing and handle navigation correctly.
You can serve multiple languages from the same page file using translation data or organize pages by locale folders.
Proper SEO setup with hreflang tags and sitemaps is essential to avoid duplicate content issues and improve search rankings.
Middleware can enhance user experience by detecting preferred language and redirecting to the correct locale path automatically.