reactjsnext.jsnext.js13app-router

Sharing User Data Between Server Components of Different Pages in Next.js 14


I am using Next.js 14 with the app router. In my main layout file, I am fetching user data using a server component and then sharing that data with a client component. I have a context provider that passes this data to the context, allowing me to easily access the user data across all client components on different pages.

However, I am facing an issue: while I can easily access the user data from the context in client components on all pages, I need to access this data in a few server components on other pages as well. How can I achieve this? Should I use cookies on the server side for this, or is there a better approach?

For now i am thiking to use the cookies but i am looking for a better option

// NOTE SERVER COMPEONTS
import React from 'react';
import DashboardApplicationsMain from '@/components/DashboardApplicationsPage';
import {
  getAllProperitesNameAction,
  getMyProperitesNameAction,
} from '@/server/property-actions';
import { GetMyPropertiesNamesActionType, UserType } from '@/types';
import { getMeAction } from '@/server/auth-actions';
import { Roles } from '@/schemas';
import { redirectBaseOnRole } from '@/server/helper';

export default async function ApplicationsPage({
  searchParams,
}: {
  searchParams?: {
    page?: string;
    propertyId?: string;
  };
}) {
  const currentPage = Number(searchParams?.page) || 1;
  const userData = (await getMeAction())?.success;
  redirectBaseOnRole(userData, [Roles.ADMIN, Roles.LANDLORD]);
  let properitesData: GetMyPropertiesNamesActionType;
  if (userData?.role === Roles.ADMIN) {
    properitesData = await getAllProperitesNameAction();
  } else properitesData = await getMyProperitesNameAction();

  return (
    <DashboardApplicationsMain
      properitesData={properitesData}
      currentPage={currentPage}
      propertyId={searchParams?.propertyId}
      userData={userData as UserType}
    />
  );
}

I need to get the user data on the server side because based on that I am fetching the Properties data


Solution

  • Depends exactly what you mean by 'server component'.

    You can pass your actual server components as props to the highest-level client component on the page, which then means that your client component can access the context and then pass it off to the server component as props.

    Or you can pass a server action as a prop to the client component and invoke it (with whatever client-accessible arguments you need) like a callback on page render or onClick or whatever is suitable.