Bird
Raised Fist0
NextJSframework~15 mins

Domain routing for locales in NextJS - Deep Dive

Choose your learning style10 modes available
Overview - Domain routing for locales
What is it?
Domain routing for locales is a way to serve different versions of a website based on the visitor's language or region by using different domain names. Instead of changing the language through URL paths or query parameters, the website automatically shows the right language version depending on the domain the user visits. For example, users visiting example.fr see the French version, while example.com shows the English version. This helps create a natural and clear experience for users from different countries.
Why it matters
Without domain routing for locales, websites often rely on URL paths or cookies to switch languages, which can confuse users and hurt search engine rankings. Using separate domains for each locale makes it easier for users to remember and trust the site, improves SEO by targeting country-specific domains, and simplifies legal or content differences per region. It also helps businesses appear local and relevant to their audience, increasing engagement and sales.
Where it fits
Before learning domain routing for locales, you should understand basic Next.js routing and internationalized routing concepts. After mastering domain routing, you can explore advanced localization techniques like dynamic content translation, user preference detection, and server-side rendering optimizations for multilingual sites.
Mental Model
Core Idea
Domain routing for locales directs users to the right language version of a website by linking each locale to its own domain name.
Think of it like...
It's like having different storefronts in different countries, each with its own sign and address, so customers naturally go to the store meant for their language and culture.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ example.com   │─────▶│ English Site  │
├───────────────┤      └───────────────┘
│ example.fr    │─────▶│ French Site   │
├───────────────┤      └───────────────┘
│ example.de    │─────▶│ German Site   │
└───────────────┘      └───────────────┘
Build-Up - 6 Steps
1
FoundationBasics of Next.js Internationalization
🤔
Concept: Learn how Next.js supports multiple languages using built-in internationalized routing.
Next.js allows you to define locales in the next.config.js file under the i18n key. This setup lets Next.js handle language detection and URL path prefixes automatically, like /en or /fr. For example: module.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en' } }; This means visiting /fr shows the French version, and /en shows English.
Result
Your Next.js app can serve different languages by URL path prefixes without extra code.
Understanding Next.js's built-in i18n routing is the foundation before adding domain-based routing.
2
FoundationWhat is Domain Routing for Locales?
🤔
Concept: Introduce the idea of using different domains instead of URL paths to serve locales.
Domain routing means assigning each locale its own domain or subdomain, like example.com for English and example.fr for French. Instead of /fr in the URL, the domain itself tells the app which language to show. This requires configuring Next.js to recognize domains and map them to locales.
Result
You see how domain routing changes the way users access localized content.
Knowing the difference between path-based and domain-based locale routing helps choose the best user experience.
3
IntermediateConfiguring Domains in next.config.js
🤔Before reading on: Do you think Next.js needs extra plugins to support domain routing for locales? Commit to your answer.
Concept: Learn how to set up domain routing by adding domain-locale mappings in Next.js configuration.
Next.js supports domain routing natively by adding a domains array inside the i18n config. Each domain object specifies the domain name and the locale it serves. For example: module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en', domains: [ { domain: 'example.com', defaultLocale: 'en' }, { domain: 'example.fr', defaultLocale: 'fr' } ] } }; This tells Next.js to serve English on example.com and French on example.fr.
Result
Next.js automatically detects the domain and serves the correct locale without URL prefixes.
Knowing that domain routing is built-in and configured declaratively simplifies implementation and maintenance.
4
IntermediateHandling Links and Navigation with Domains
🤔Before reading on: Will Next.js automatically switch domains when using the Link component for locale changes? Commit to your answer.
Concept: Understand how Next.js manages links and navigation when using domain routing for locales.
When you use the Next.js component or router.push to change locales, Next.js automatically switches the domain if domain routing is configured. For example, navigating from example.com to the French version will redirect to example.fr. This keeps the user on the correct domain for their language. Example: import Link from 'next/link'; French Home This link will send users to example.fr automatically.
Result
Users experience seamless navigation between domains without manual URL changes.
Understanding automatic domain switching prevents broken links and improves user experience.
5
AdvancedSEO and Cookies with Domain Routing
🤔Before reading on: Do you think cookies set on one domain are accessible on another domain? Commit to your answer.
Concept: Explore how domain routing affects SEO and cookie handling for localized sites.
Each domain is treated as a separate site by browsers and search engines. This means cookies set on example.com are not shared with example.fr. For SEO, using country-code top-level domains (ccTLDs) like .fr or .de helps search engines target the right audience. However, you must configure hreflang tags properly to avoid duplicate content issues. Example hreflang:
Result
Your site ranks better in local search results and respects user privacy per domain.
Knowing domain isolation helps design cookie strategies and SEO setups that respect locale boundaries.
6
ExpertCustom Server and Middleware for Domain Routing
🤔Before reading on: Is Next.js middleware required to detect locale from domain in domain routing? Commit to your answer.
Concept: Learn how to use Next.js middleware or custom server logic to enhance or customize domain routing behavior.
While Next.js supports domain routing out of the box, advanced use cases may require middleware to handle edge cases like locale fallback, redirects, or custom headers. Middleware runs before rendering and can inspect the request domain to set locale cookies or rewrite URLs. Example middleware snippet: import { NextResponse } from 'next/server'; export function middleware(request) { const hostname = request.headers.get('host'); if (hostname === 'example.fr') { return NextResponse.rewrite(new URL('/fr' + request.nextUrl.pathname, request.url)); } return NextResponse.next(); } This allows fine control beyond config settings.
Result
You can customize locale detection and routing logic for complex scenarios.
Understanding middleware empowers you to handle edge cases and improve user experience beyond defaults.
Under the Hood
Next.js reads the incoming request's domain name from the HTTP headers. It matches this domain against the configured domains in next.config.js under the i18n.domains array. Once matched, Next.js sets the locale for the request context, which affects page rendering, routing, and link generation. This happens early in the request lifecycle, ensuring the correct language content is served. When navigating client-side, Next.js updates the URL and domain accordingly, maintaining locale consistency.
Why designed this way?
Domain routing was designed to provide a natural and SEO-friendly way to serve localized content without relying on URL paths or cookies alone. Using domains leverages existing web infrastructure like DNS and browser security models, making locale detection reliable and transparent. Alternatives like path-based routing were simpler but less intuitive for users and search engines. Domain routing balances user experience, SEO, and technical feasibility.
┌───────────────┐
│ Incoming HTTP │
│ Request       │
└──────┬────────┘
       │ Host header
       ▼
┌───────────────┐
│ Domain Match  │
│ (next.config) │
└──────┬────────┘
       │ Locale set
       ▼
┌───────────────┐
│ Locale-aware  │
│ Rendering     │
└──────┬────────┘
       │ Client-side
       │ navigation
       ▼
┌───────────────┐
│ Correct Domain│
│ & Locale URL  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does setting domain routing in next.config.js automatically handle all locale redirects perfectly? Commit to yes or no.
Common Belief:Once domain routing is configured, Next.js automatically redirects all users to the correct domain without extra setup.
Tap to reveal reality
Reality:Next.js handles locale detection and routing, but you may need additional redirects or middleware to cover all edge cases like non-localized URLs or fallback locales.
Why it matters:Assuming automatic redirects can cause users to see wrong locales or broken links, harming user experience and SEO.
Quick: Can cookies set on example.com be read by example.fr? Commit to yes or no.
Common Belief:Cookies set on one domain are accessible on all locale domains of the same website.
Tap to reveal reality
Reality:Cookies are domain-specific and cannot be shared across different domains, even if they belong to the same site owner.
Why it matters:Misunderstanding cookie scope can cause bugs in user sessions, preferences, or authentication across locales.
Quick: Does domain routing replace the need for hreflang tags in SEO? Commit to yes or no.
Common Belief:Using different domains for locales means you don't need hreflang tags for SEO.
Tap to reveal reality
Reality:Hreflang tags are still necessary to tell search engines about alternate language versions and avoid duplicate content penalties.
Why it matters:Skipping hreflang tags can hurt search rankings and confuse search engines about your site's language targeting.
Quick: Is domain routing only useful for large websites? Commit to yes or no.
Common Belief:Domain routing is only beneficial for big companies with many locales.
Tap to reveal reality
Reality:Even small or medium sites benefit from domain routing for clear branding, user trust, and SEO advantages.
Why it matters:Ignoring domain routing limits growth potential and user experience in international markets.
Expert Zone
1
Domain routing requires careful SSL certificate management for each domain to avoid security warnings.
2
Edge caching and CDN configurations must consider domain routing to serve localized content efficiently.
3
Middleware can introduce latency if not optimized, so use it sparingly and cache results when possible.
When NOT to use
Avoid domain routing if your site has very few locales or if managing multiple domains is too costly or complex. Instead, use path-based locale routing or subdomains. Also, if your audience is mostly global with no strong regional preferences, domain routing may add unnecessary complexity.
Production Patterns
Large e-commerce sites use domain routing to serve country-specific stores with localized pricing and legal terms. News websites use it to deliver region-specific content. Middleware is often used to handle locale fallbacks and user preference overrides. SEO teams configure hreflang tags and canonical URLs carefully to maximize search visibility.
Connections
Internationalized Routing
Domain routing is an extension of internationalized routing that uses domains instead of URL paths.
Understanding internationalized routing helps grasp how domain routing fits as a more user-friendly and SEO-optimized approach.
DNS and SSL Management
Domain routing depends on DNS configuration and SSL certificates for each domain.
Knowing DNS and SSL basics is crucial to implement domain routing securely and reliably.
Branding and Marketing Strategy
Domain routing supports branding by giving each locale its own domain identity.
Recognizing the marketing impact of domain routing helps align technical choices with business goals.
Common Pitfalls
#1Not configuring domains array in next.config.js causes domain routing to fail.
Wrong approach:module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en' } };
Correct approach:module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en', domains: [ { domain: 'example.com', defaultLocale: 'en' }, { domain: 'example.fr', defaultLocale: 'fr' } ] } };
Root cause:Forgetting to add the domains array means Next.js doesn't know which domains map to which locales.
#2Using relative links without locale attribute breaks domain switching.
Wrong approach:About
Correct approach:À propos
Root cause:Not specifying locale in links prevents Next.js from switching domains correctly.
#3Setting cookies on one domain expecting them on another domain.
Wrong approach:document.cookie = 'user=123; path=/;'; // on example.com // expecting cookie on example.fr
Correct approach:// Set cookies separately on each domain or use server-side session management.
Root cause:Cookies are isolated per domain by browser security policies.
Key Takeaways
Domain routing for locales uses different domains to serve language-specific versions of a website, improving user experience and SEO.
Next.js supports domain routing natively through the i18n.domains configuration in next.config.js.
Proper link handling and SEO practices like hreflang tags are essential to make domain routing effective.
Cookies and sessions are domain-specific, so managing user data across domains requires special care.
Advanced scenarios may need middleware or custom server logic to handle edge cases and optimize performance.

Practice

(1/5)
1. What is the main purpose of domain routing for locales in Next.js?
easy
A. To enable client-side routing only
B. To improve server performance by caching
C. To create multiple apps in one project
D. To serve different languages on different domains

Solution

  1. Step 1: Understand domain routing concept

    Domain routing allows serving different languages or locales on separate domains or subdomains.
  2. Step 2: Identify the main use case in Next.js

    Next.js uses domain routing to link domains to specific locales for internationalization.
  3. Final Answer:

    To serve different languages on different domains -> Option D
  4. Quick Check:

    Domain routing = serve languages on domains [OK]
Hint: Domain routing connects domains to languages [OK]
Common Mistakes:
  • Confusing domain routing with caching
  • Thinking it only affects client-side routing
  • Assuming it creates multiple apps
2. Which Next.js config property is used to define domain routing for locales?
easy
A. routing.locales
B. i18n.domains
C. locales.domains
D. next.config.domains

Solution

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

    The internationalization config uses the i18n key in next.config.js.
  2. Step 2: Identify the property for domain routing

    The correct property to define domain-locale mapping is i18n.domains.
  3. Final Answer:

    i18n.domains -> Option B
  4. Quick Check:

    Domain routing config = i18n.domains [OK]
Hint: Look inside i18n config for domains key [OK]
Common Mistakes:
  • Using next.config.domains instead of i18n.domains
  • Confusing with routing.locales
  • Trying to set domains outside i18n
3. Given this Next.js i18n config snippet, what locale will be served for requests to https://example.fr?
i18n: {
  locales: ['en', 'fr'],
  defaultLocale: 'en',
  domains: [
    { domain: 'example.com', defaultLocale: 'en' },
    { domain: 'example.fr', defaultLocale: 'fr' }
  ]
}
medium
A. fr
B. en
C. defaultLocale from browser
D. No locale, error occurs

Solution

  1. Step 1: Check domain-locale mapping in config

    The domain example.fr is mapped to fr locale explicitly.
  2. Step 2: Determine locale served for example.fr

    Requests to example.fr will serve the French locale fr.
  3. Final Answer:

    fr -> Option A
  4. Quick Check:

    example.fr domain = fr locale [OK]
Hint: Match domain to locale in i18n.domains array [OK]
Common Mistakes:
  • Assuming defaultLocale 'en' applies to all domains
  • Thinking browser locale overrides domain
  • Believing error occurs without explicit locale
4. You wrote this middleware to detect locale by domain but it always serves the default locale. What is the likely mistake?
export function middleware(request) {
  const hostname = request.headers.get('host')
  if (hostname === 'example.fr') {
    return NextResponse.rewrite(new URL('/fr', request.url))
  }
  return NextResponse.next()
}
medium
A. Rewriting to '/fr' instead of setting locale cookie
B. Not returning a response for all domains
C. Using 'host' header instead of 'x-forwarded-host'
D. Middleware missing 'export default'

Solution

  1. Step 1: Understand middleware role in locale detection

    Middleware should set locale or rewrite URL to include locale prefix properly.
  2. Step 2: Identify issue with rewriting only

    Rewriting to '/fr' alone may not set locale context; locale cookie or header is needed for Next.js to recognize locale.
  3. Final Answer:

    Rewriting to '/fr' instead of setting locale cookie -> Option A
  4. Quick Check:

    Middleware must set locale, not just rewrite URL [OK]
Hint: Middleware must set locale, not just rewrite URL [OK]
Common Mistakes:
  • Assuming host header is wrong
  • Forgetting to handle all domains
  • Missing export default in middleware
5. How would you configure Next.js to serve English on 'example.com' and French on 'example.fr' using domain routing, ensuring the default locale is English and URLs do not show locale prefixes?
hard
A. Set i18n.locales to ['en', 'fr'], defaultLocale to 'en', and i18n.domains with domains for example.com (fr) and example.fr (en), and use localeDetection: true
B. Set i18n.locales to ['en', 'fr'], defaultLocale to 'fr', and i18n.domains with domains for example.com (fr) and example.fr (en), and use localeDetection: true
C. Set i18n.locales to ['en', 'fr'], defaultLocale to 'en', and i18n.domains with domains for example.com (en) and example.fr (fr), and use localeDetection: false
D. Set i18n.locales to ['en', 'fr'], defaultLocale to 'en', and no domains, rely on middleware only

Solution

  1. Step 1: Define locales and defaultLocale correctly

    Locales should be ['en', 'fr'] with defaultLocale 'en' to serve English by default.
  2. Step 2: Configure i18n.domains for domain-locale mapping

    Map 'example.com' to 'en' and 'example.fr' to 'fr' in i18n.domains array.
  3. Step 3: Disable localeDetection to avoid prefix in URLs

    Setting localeDetection: false prevents Next.js from adding locale prefixes in URLs, serving clean domain-based locales.
  4. Final Answer:

    Set i18n.locales to ['en', 'fr'], defaultLocale to 'en', and i18n.domains with domains for example.com (en) and example.fr (fr), and use localeDetection: false -> Option C
  5. Quick Check:

    Domain routing + defaultLocale + no prefix = Set i18n.locales to ['en', 'fr'], defaultLocale to 'en', and i18n.domains with domains for example.com (en) and example.fr (fr), and use localeDetection: false [OK]
Hint: Use i18n.domains and disable localeDetection for clean URLs [OK]
Common Mistakes:
  • Swapping locales for domains
  • Forgetting to disable localeDetection
  • Relying only on middleware without domains
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