Skip to content

Save language selction local storage or cookie #1201

Answered by aralroca
MuhammadSaim asked this question in Q&A
Discussion options

You must be logged in to vote

I hope this documentation helps: https://github.com/aralroca/next-translate?tab=readme-ov-file#11-how-to-save-the-user-defined-language:

import { useRouter } from 'next/router'

// ...

function usePersistLocaleCookie() {
    const { locale, defaultLocale } = useRouter()

    useEffect(persistLocaleCookie, [locale, defaultLocale])
    function persistLocaleCookie() {
      if(locale !== defaultLocale) {
         const date = new Date()
         const expireMs = 100 * 24 * 60 * 60 * 1000 // 100 days
         date.setTime(date.getTime() + expireMs)
         document.cookie = `NEXT_LOCALE=${locale};expires=${date.toUTCString()};path=/`
      }
    }
}

The cookie name should be NEXT_LOCALE, t…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@MuhammadSaim
Comment options

Answer selected by MuhammadSaim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants