next.jscookieslocalizationlocal-storage

using NextJS cookies in order to remember user preferences


I'm using NextJS 13 for my react app and I have implemented multi language options for the user to choose from with English being the default.

As far as how its currently implemented, the language is in the url as in 'example.com/en', and the relevant language dictionary is being passed from the server side through the server components to where its needed.

import { getDictionary } from "@/lib/dictionary";
import { Locale } from "@/i18n.config";
import { cookies } from 'next/headers'

export default async function Home({
  params: { lang }
}: {
  params: { lang: Locale }
}) {

  const { navigation , page } = await getDictionary(lang);
  const { home } = page;
 return (
// JSX...
);
}

Id like to implement somehow that the default language for the user will be the last one that the user chose, and I'm not sure how or where to begin.

Should I do it using cookies, local storage or maybe something else?

Thank you


Solution

  • It depends on your requirements (You can go with local storage or cookies or even combine them), but to help you breaking it up:

    Sooo, Local storage is only available on the client side. So if you want to use it, you can create a hook with a

    if (typeof window !== 'undefined'){
       // Accessing Local storage
    }
    

    You can check this: https://hackernoon.com/storing-and-retrieving-data-in-nextjs-using-localstorage-and-typescript

    For cookies, you can also use them on the client side with next-client-cookies

    Also, if you use a localization library like i18nexus it saves the locale in the cookies too (NEXT_LOCALE) :) You can check this tutorial for it https://i18nexus.com/tutorials/nextjs/react-i18next

    For me, I would use cookies.

    Hope this answer helps!