Bird
Raised Fist0
NextJSframework~15 mins

Sub-path routing for locales in NextJS - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of sub-path routing for locales in Next.js?
easy
A. To create separate apps for each language without sharing code.
B. To serve different language versions of the site using URL prefixes like /en or /fr.
C. To load all languages at once on the homepage.
D. To disable internationalization features in Next.js.

Solution

  1. Step 1: Understand sub-path routing concept

    Sub-path routing uses URL parts like /en or /fr to show different language versions of the same site.
  2. Step 2: Compare options

    Only To serve different language versions of the site using URL prefixes like /en or /fr. correctly describes this purpose. Other options describe unrelated or incorrect behaviors.
  3. Final Answer:

    To serve different language versions of the site using URL prefixes like /en or /fr. -> Option B
  4. Quick Check:

    Sub-path routing = URL prefixes for languages [OK]
Hint: Remember: sub-path routing adds language code in URL path [OK]
Common Mistakes:
  • Thinking sub-path routing loads all languages at once
  • Confusing sub-path routing with separate apps per language
  • Believing it disables i18n features
2. Which is the correct way to configure supported locales in next.config.js for sub-path routing?
easy
A. "i18n: ['en', 'fr'], defaultLocale: 'en'"
B. "locales: ['en', 'fr'], default: 'en'"
C. "i18n: { languages: ['en', 'fr'], defaultLang: 'en' }"
D. "i18n: { locales: ['en', 'fr'], defaultLocale: 'en' }"

Solution

  1. Step 1: Recall Next.js i18n config structure

    The correct config uses the i18n object with locales array and defaultLocale string.
  2. Step 2: Match options to correct syntax

    "i18n: { locales: ['en', 'fr'], defaultLocale: 'en' }" matches the exact syntax. Others use wrong keys or structure.
  3. Final Answer:

    "i18n: { locales: ['en', 'fr'], defaultLocale: 'en' }" -> Option D
  4. Quick Check:

    i18n config = locales + defaultLocale [OK]
Hint: Look for 'i18n' key with 'locales' and 'defaultLocale' [OK]
Common Mistakes:
  • Using wrong keys like 'languages' or 'defaultLang'
  • Not wrapping locales inside 'i18n' object
  • Using arrays without keys
3. Given this Next.js page code snippet, what will be rendered if the URL is /fr?
import { useRouter } from 'next/router';
export default function Home() {
  const { locale } = useRouter();
  return <div>Current language: {locale}</div>;
}
medium
A. Current language: undefined
B. Current language: en
C. Current language: fr
D. Error: useRouter() not found

Solution

  1. Step 1: Understand useRouter locale property

    The useRouter hook provides the current locale from the URL sub-path like /fr.
  2. Step 2: Match URL to locale value

    Since URL is /fr, locale will be 'fr', so the rendered text is "Current language: fr".
  3. Final Answer:

    Current language: fr -> Option C
  4. Quick Check:

    URL /fr sets locale = 'fr' [OK]
Hint: Locale matches URL sub-path prefix [OK]
Common Mistakes:
  • Assuming default locale always shows
  • Thinking locale is undefined without explicit code
  • Confusing useRouter hook usage
4. Identify the error in this Next.js next.config.js snippet for locale sub-path routing:
module.exports = {
  i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'en',
    localeDetection: true,
  },
};
medium
A. The config is correct and will enable sub-path routing with locale detection.
B. localeDetection is not a valid option inside i18n.
C. locales must include the default locale twice.
D. localeDetection should be localeDetection: false to enable sub-path routing.

Solution

  1. Step 1: Check valid i18n config options

    Next.js supports localeDetection inside i18n to enable or disable automatic locale detection.
  2. Step 2: Verify given config

    The config has valid keys and values. Setting localeDetection: true enables automatic detection, which is allowed.
  3. Final Answer:

    The config is correct and will enable sub-path routing with locale detection. -> Option A
  4. Quick Check:

    localeDetection is valid and true means enabled [OK]
Hint: Check Next.js docs for valid i18n keys [OK]
Common Mistakes:
  • Thinking localeDetection is invalid
  • Believing localeDetection must be false for sub-path routing
  • Duplicating default locale in locales array
5. You want to create a Next.js app supporting English and French with sub-path routing. You want the default locale to be English and URLs like /fr/about to show French content. Which steps are needed to correctly configure this? A) Set i18n.locales to ['en', 'fr'] and defaultLocale to 'en' in next.config.js. B) Use useRouter() in pages to get locale and show language-specific content. C) Create folders or files under app or pages to handle routes for each locale. D) Disable locale detection to force manual locale switching.
hard
A. Only A, B, and C are needed.
B. All A, B, C, and D are needed.
C. Only A and B are needed.
D. Only B and D are needed.

Solution

  1. Step 1: Configure locales and defaultLocale

    Setting i18n.locales and defaultLocale in next.config.js enables sub-path routing for English and French.
  2. Step 2: Use useRouter to get locale and show content

    Using useRouter() to get locale helps render language-specific content dynamically.
  3. Step 3: Organize routes for each locale

    Creating folders or files under app or pages supports localized routes like /fr/about.
  4. Step 4: Evaluate locale detection setting

    Disabling locale detection is optional and not required to support sub-path routing correctly.
  5. Final Answer:

    Only A, B, and C are needed. -> Option A
  6. Quick Check:

    Locales config + useRouter + route files = correct setup [OK]
Hint: Remember: locale config + router + route files are key [OK]
Common Mistakes:
  • Thinking disabling locale detection is mandatory
  • Not creating route files for localized paths
  • Ignoring useRouter for locale detection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard