user15030566
user15030566

Reputation:

How to force default locale in the URL when clicking a link in Next.js

For the SEO purposes I need to set up English as default language -> mynextapp.com/ when user enters the website, he/she can choose between ENGLISH or FRENCH, if English is selected the url will change to mynextapp.com/en, if the French will be chosen -> mynextapp.com/fr

Currently I am using the build in option in Next - i18n:

i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'en',
},

But this allows me to have English only as a default path = mynextapp.com/

Language Switcher:

    <Link
        href="/"
        locale={router.locale === 'en' ? 'fr' : 'en'}
    >
        <a>Switch</a>
    </Link>

Is there a way how to handle the same language under different urls? So that when you click on "en" in language switcher, the url path should be myapp.com/en.

Upvotes: 8

Views: 20427

Answers (3)

Eunit
Eunit

Reputation: 146

How to use?

import { useLocale } from "next-intl";

...

  console.log(useLocale()); // en

Upvotes: 0

Ashkan Pourghasem
Ashkan Pourghasem

Reputation: 748

For future reference, I managed to get my code working by routing to the other language (2 locales, one of them default) and have the default prefix always in the URL by using the following redirecting logic in my language switcher:

i18n.changeLanguage(i18n.language === Locales.EN ? Locales.NL : Locales.EN);
router.push(
  `/${i18n.language}${router.pathname}`,
  `/${i18n.language}${router.asPath}`,
  {
    locale: false
  }
);

Upvotes: 0

juliomalves
juliomalves

Reputation: 50278

To force the default language to add the locale to the URL you could pass it to the href directly, and opt-out of automatically handling the locale prefixing by setting locale to false.

<Link href={`/${router.locale === 'en' ? 'fr' : 'en'}`} locale={false}>
    <a>Switch</a>
</Link>

If you want all your Links to behave this way, and also force the default locale on the URL, the same logic would need to be applied.

Assuming you have a link to the /about page, it would look like the following.

<Link href={`/${router.locale}/about`} locale={false}>
    <a>About Page</a>
</Link>

If using next/router to do the routing, the same logic can also be applied.

router.push(`/${router.locale}/about`, undefined, { locale: false });

Upvotes: 6

Related Questions