How to retrieve the locale from the cookies / headers
Using Hooks (Recommended)
For most use cases, it is recommended to retrieve the current locale using the useLocale hook because it is auto-resolved. This works similarly to the useLocale composable in Vue.js.
Copy the code to the clipboard
For server components, you can import it from:
Copy the code to the clipboard
There is also a useLocaleCookie hook that only resolves the cookie value.
Manual Cookie Configuration
You can declare a custom cookie name as
Copy the code to the clipboard
the retrieve it as
Client-side
Copy the code to the clipboard
Server-side (Next.js)
Copy the code to the clipboard
If locale not set yet
The locale is set as a cookie only once the user explicitly selects the locale. By default, for new visitors, the locale is interpreted from the header fields.
You can detect the user's preferred locale from the request headers. Here's an example of how to handle this:
Copy the code to the clipboard