Storing selected language option in cookie/localSession

Viewed 3389

I would like my Next.js app to remember which language the user prefers, therefore I want to store it in a cookie on client side. I have 2 language options: EN & FR.

By default the language is set up for English (no cookie, myapp.com/), but once the user clicks on EN preference, the URL changes to myapp.com/en and this selected language should be stored. The same applies for French.

const [language, setLanguage] = useState(false);

        <Link
            href={`/${router.locale === 'en' ? 'fr' : 'en'}`}
            locale={false}
        >
            <a
                onClick={() => {
                    setLanguage((language) => !language);
                    // setCookie({});
                }}
            >
                {` ${language ? 'en' : 'fr'}`}
            </a>

Where and how can I use the cookie or session storage so the backend can see it?

1 Answers

You can leverage the NEXT_LOCALE cookie to persist the user's language preference. This will override the accept-language header that is usually used by Next.js built-in i18n.

This function sets a cookie with an expiry date of one year from now, at the root path of the domain.

const setCookie = (locale) => {
    document.cookie = `NEXT_LOCALE=${locale}; max-age=31536000; path=/`
}

Recommendation: Unrelated to the issue you raised, I would also recommend you use a button rather than an anchor to handle the language switching, as it's doing more than just simple navigation at this point.

<button
    onClick={() => {
        const locale = router.locale === 'en' ? 'fr' : 'en'
        setCookie(locale)
        router.push(router.asPath, undefined, { locale })
    }}
>
    {router.locale === 'en' ? 'fr' : 'en'}
</button>
Related