0
0
NextJSframework~15 mins

Domain routing for locales in NextJS - Deep Dive

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