Return to Blog Home

Many domains to one Next.js

 Live

Many domains to one Next.js

One server, two domains, infinite possibilities!

To provide a bit of background, I was hosting my website on some random cheep VPS, and was using Apache to redirect all traffic to my running Next.js instance.

After taking a peek at the Internationalized Routing documentation, I started moving the data I wanted to change into my next.config.js publicRuntimeConfig object, keyed under each variant of the website:

ab: {
  name: 'Name',
  ...
}

Then in the i18n property I added my two domains, with the custom locale language tag and finally disabled locale detection:

i18n: {
  locales: ['ab', 'cd'],
  defaultLocale: 'ab',
  localeDetection: false,
  domains: [
    {
      domain: 'example.com',
      defaultLocale: 'ab',
    },
    {
      domain: 'example.com',
      defaultLocale: 'cd',
    }
  ]
}

Lastly I wrapped the fetching of this data up on the frontend into a nice little hook:

export const useLocaleConfig = () => getConfig().publicRuntimeConfig[useRouter().locale] as {
  name: string,
  links: Record<string, string>
}

Of course I had to make my components receive what was previous hardcoded as props, but that was extremely easy to do.

Host Stripping

Unfortunately when I had deployed it, only one of the domains was working: the default one.

My hypothesis at this point was that Apache was somehow stripping the host information when proxying the request to the server, and after doing some logging-in-production, I was sure this was the issue.

After a bit of time searching, I found ProxyPreserveHost On, which made it work!