Next.js Discord

Discord Forum

"Universal" function to get a specific value according to component type (Server or Client)

Unanswered
Ninhache posted this in #help-forum
Open in Discord
The specific value is the locale :
- In ServerComponents : getLocale() -> Server Context can only be used in a Server Component
- In ClientComponents : usePathname() -> Hooks can only be used in a Client Component
----
Here's my current function :
export const t = (locale, nsKey) => {
  const dictionary = getDictionary(locale)
  return getNestedValue(dictionary, nsKey)
}

^ This function intents are to reproduce i18n feature.. to be able to get text from a key like that :
t('form.classic.name')
But in my function, i've to specify the lang, and I want to get rid of that :

My idea was to use typeof window === undefined to know if i'm in a client component or in a server one
But there's still a main problem :
how i could get the langage... ?!
As i've explained above, in each "part" (Client / Server), I know how i can get those values, but each comes with his problems :
- In my server's components, i've setup a server-context, that can provide the langage.. cool 👍
But i can't use it in a Client Component, or i will get a runtime error
- In my client components, i don't know, i usually use the usePathname hooks, but i can't use it out of a component and i can't use it by not specifying the use client directive

Any idea to how i can solve my problem ?
Using App Router 🤓

18 Replies

Is this even possible* ? 🤠
i've updated the way i've explained
I don't think that's easily possible. Use separate functions for client/server. That's how the libraries I've used handle it too.
Idk how i could easily get the lang.. even if i try to do it in 2 functions, i can't really use the hooks/context outside of the components..
check out the i18next guide for app directory. They explain how to do that in server components
yeah that's it
i've find that a month ago and i'd tried to implement it..
something wasnt working
i'm gonna retry
If you don't want to deal with a third-party package you can use the template provided in Next.js' examples. It's a really good starting point imo

https://github.com/vercel/next.js/tree/canary/examples%2Fapp-dir-i18n-routing
But i wanna get rid of the lang in all props
that's why i've setup a server context
but i'd a problem for client component..
for client i were using pathname lmao
Why would you try to get the lang this way? You can pass it down from your layout wherever you need it. And if you want to avoid prop drilling make a context provider that holds that value and use it with a hook in your client components