I'm currently looking for a good way to exchange data between my components in NextJS 14. For SEO reasons, I am currently switching my client-side API fetches to server-side. I encountered the following problems:
I need headers and cookies functions for authentication in order to read API keys and pass them on during fetch.
I need functions like cookies()
or headers()
for authentication in order to read API keys and pass them on during fetch. The problem is that hey can only be called from page components. So if I have a landing page and want to display a profile settings popup with data, I would have to load the data at the page component level even though the popup hasn't opened yet. Since I want to avoid this, all I can do is load the session cookie when the page is called and distribute it to the other components that have to do the fetches.
I have a simple i18n implementation without third party librarians.
This is server only so that I can use it with server components and pass the translation data to underlying client components if required. In order to load the language according to the URL (via dynamic routes), I need access to the dynamic routes parameters
export default async function APageComponent({ params: { lang } } : { params: { lang: Locale } } ) {
.
In some components there are links that should also contain the path with the current language. Since I don't have access to the dynamic routes URL parameters in the other components, I would also have to pass them from component to component, which would also be unpleasant.
In both cases, the data could be passed on to the underlying components as props. But this would involve massive props drilling. Aren't there better solutions that work similarly to Redux or the ContextAPI, which are also applicable to Server components?
So far I have tried to simply pass the data as props to the underlying components. So I had set the props language={lang}
and session={sessionCookie}
for most components in order to either specify the path with the correct language for the links or to be able to make API calls with the session cookie.
Addressing your first question: The cookies function can be used in any server component, not only page or layout, also another thing you should know is that using it withing a layout or page would opt the route into dynamic rendering at request time, so if you have a popup component, you can render it server side and use the cookies function to retrieve the desired cookie.
Addressing your second question:
For pages and layouts, you can only retrieve the params from props the way you are doing it, for other server components, they have to be passed as props.
For client components, there's the useParams
hook that you can use, it returns an object that includes all the dynamic parameters in your route with their value.