Using NextJS cookies in order to remember user preferences

clock icon

asked 2 months ago

message

1 Answers

eye

15 Views

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

1 Answers

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

  • Local storage persists even after the browser is closed and reopened, making it good for storing user preferences that should be maintained across sessions, but it won't be available during the SSR.
  • Session storage is only available for the duration of the page session, and it won't be available during the SSR. So it is not really an option for the language, I suppose.
  • With Cookies 🍪 it is useful for server-side operations.

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!

Top Questions