Next.js Discord

Discord Forum

Per domain localization

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Hey everyone. Has anyone found a good way to do per-domain localization in the App Router? E.g. store.fr would be served in French while store.com would be served in English. Perhaps some kind of URL rewrite for .fr to store.com/fr would solve it?

It would be best if I could avoid using middleware.

8 Replies

Rhinelander
javascript 
module.exports = {
  i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'en',
    localeDetection: true,
  },
};
import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const browserLang = navigator.language || navigator.userLanguage;
    const supportedLocales = ['en', 'fr'];

    let detectedLocale = 'en'; // fallback to 'en-US' if the browser's language is not supported
    if (supportedLocales.includes(browserLang)) {
      detectedLocale = browserLang;
    }

    // If the user hits the root path, redirect based on the browser's language
    if (router.pathname === '/') {
      router.replace(`/${detectedLocale}`);
    }
  }, [router.pathname]);

  return <Component {...pageProps} />;
}
import { getStaticProps } from 'next';
import IpGeolocation from 'ip-geolocation';

export async function getStaticProps() {
  const ipGeolocation = new IpGeolocation('YOUR_API_KEY');
  const userIp = '192.168.1.1'; // Replace with the user's IP address
  const userLocation = await ipGeolocation.byIp(userIp);

  // Use the user's location to determine the language
  const userLanguage = userLocation.country.toLowerCase();

  return {
    props: {
      userLanguage,
    },
  };
}
import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function MyApp({ Component, pageProps }) {
  const router = useRouter();
  const userLanguage = pageProps.userLanguage;

  useEffect(() => {
    // Redirect based on the user's location
   if (userLanguage === 'fr') {
      router.replace('/fr');
    } 
  }, [router]);

  return <Component {...pageProps} />;
}
And at "/fr" just redirect to other domain
Asian black bearOP
But how would store.fr know that it should serve French locale?
I don't want any automatic detection of locales or anything like that. But basically:

store.com - serve English content (en locale)
store.fr - serve French content (fr locale)
Asian black bearOP
Ok I managed to solve this with next-intl, but ofc this requires running middleware for all routes 😦