Domain routing for locales lets your website show different languages or content based on the website address people use. It helps visitors see the right version automatically.
0
0
Domain routing for locales in NextJS
Introduction
You want visitors from different countries to see your site in their language automatically.
You have multiple websites with different domain names for each language or region.
You want to improve user experience by showing local content based on the domain.
You want to manage language versions without changing the URL path.
You want search engines to recognize different domains for different languages.
Syntax
NextJS
module.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en', domains: [ { domain: 'example.com', defaultLocale: 'en' }, { domain: 'example.fr', defaultLocale: 'fr' }, { domain: 'example.de', defaultLocale: 'de' } ] } };
This code goes inside next.config.js to tell Next.js about your locales and domains.
The domains array links each domain to a default language.
Examples
This example sets up English and Spanish with two domains.
NextJS
module.exports = { i18n: { locales: ['en', 'es'], defaultLocale: 'en', domains: [ { domain: 'mysite.com', defaultLocale: 'en' }, { domain: 'mysite.es', defaultLocale: 'es' } ] } };
This example uses English and Japanese with separate domains.
NextJS
module.exports = { i18n: { locales: ['en', 'ja'], defaultLocale: 'en', domains: [ { domain: 'example.com', defaultLocale: 'en' }, { domain: 'example.jp', defaultLocale: 'ja' } ] } };
Sample Program
This example configures two domains for English and French. The page shows a greeting based on the current locale detected from the domain.
NextJS
/* next.config.js */ module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en', domains: [ { domain: 'myapp.com', defaultLocale: 'en' }, { domain: 'myapp.fr', defaultLocale: 'fr' } ] } }; /* pages/index.js */ import { useRouter } from 'next/router'; export default function Home() { const { locale } = useRouter(); return ( <main> <h1>{locale === 'fr' ? 'Bonjour!' : 'Hello!'}</h1> <p>{locale === 'fr' ? 'Bienvenue sur notre site.' : 'Welcome to our site.'}</p> </main> ); }
OutputSuccess
Important Notes
Make sure your DNS and hosting are set up to point each domain to your Next.js app.
Next.js automatically detects the locale from the domain and serves the right content.
You can add more domains and locales by extending the domains array.
Summary
Domain routing lets you serve different languages on different website addresses.
Configure domains and locales in next.config.js under the i18n key.
Your app can show content based on the detected locale from the domain.