Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts

export const validateRequest = cache(
  async (): Promise<
    { user: LuciaUser; session: Session } | { user: null; session: null }> => {
    await dbConnect();
    const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null;
    if (!sessionId) {
      return {
        user: null,
        session: null,
      };
    }

    const result = await lucia.validateSession(sessionId);

    if (!result) {
      return {
        user: null,
        session: null,
      };
    }

    const profileAttributes = await getProfileAttributes(result.user);

    if (!profileAttributes) {
      return {
        user: null,
        session: null,
      };
    }
    result.user.profile = {
      ...profileAttributes,
      
      _id: undefined,
      id: profileAttributes._id,
    };

    try {
      if (result.session && result.session.fresh) {
        const sessionCookie = lucia.createSessionCookie(result.session.id);
        cookies().set(
          sessionCookie.name,
          sessionCookie.value,
          sessionCookie.attributes
        );
      }
      if (!result.session) {
        const sessionCookie = lucia.createBlankSessionCookie();
        cookies().set(
          sessionCookie.name,
          sessionCookie.value,
          sessionCookie.attributes
        );
      }
    } catch (error) {
      console.log('error message', error);
    }
    return JSON.parse(JSON.stringify(result));
  }
);


Trying to fetch data in a server component may seem simple, as shown below:

export default async function Home() {
  const { user } = await validateRequest();
return(

<>
{user? (
<h2 className="text-2xl font-semibold text-gray-900 dark:text-white">
   Welcome, {user?.profile?.firstName}!
</h2> ):(
<>
<Link href="/auth/login">
 Go to Login
 <LogIn />
 </Link>
</>

)

</>

When applying the same logic in a client component, I encountered numerous issues and have been struggling to find a solution for a while now.

If anyone could provide guidance on what steps to take, it would be greatly appreciated for my learning and future reference. Thank you in advance.

Answer №1

Incorporate the API call within the layout.ts file and once the user data is retrieved, save it in a state management tool such as Redux or Zustand. This way, you can easily access the data in any component. If the component is part of the layout itself, like a navbar or footer, there's no need for a separate store - simply pass the data directly from layout.ts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for bypassing the 4mb API Routes body size limit?

I've been experimenting with different methods to bypass the body size limit in API Routes. https://nextjs.org/docs/messages/api-routes-body-size-limit Establishing a custom server (Basic Express App) Passing a custom config for bodyParser sizeLimit ...

Unexpected outcomes experienced with AJAX in ASP.NET due to javascript integration

I experimented with two methods (server and client side) for initiating a JavaScript AJAX call to post a ticket on a website and then retrieve a link containing the ticket number for tracking or editing purposes. However, both approaches yielded different ...

transforming PDF into an Image using PhantomJS

Currently, I am using PhantomJs to convert webpages into images successfully. Here is the code snippet I am using: phantomjs.exe rasterize.js http://myurl.com/mypage/ out_put_image.png Even though this method works well for webpages, it encounters an iss ...

main.js:1 ERROR TypeError: Unable to access property 'querySelectorAll' of null

I am currently using Chartist in conjunction with Angular to generate charts. However, I am encountering a problem where the charts do not display when the server is running, and an error appears on the console. Strangely enough, refreshing the page caus ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

Ways to enhance an image by zooming in when the user reaches a designated area on the webpage

I have implemented a feature where an image zooms in to letter L when the user scrolls on the page. However, I want this zoom effect to occur only when the user reaches a specific section of the site, rather than immediately when the image loads. In my exa ...

Tips for eliminating contenthash (hash) from the names of JavaScript and CSS files

Google's cached pages are only updated once or twice a day, which can result in broken sites on these cached versions. To prevent this issue, it is recommended to remove the contenthash from the middle of the filename for JavaScript files and eliminat ...

Instantly see changes without having to manually refresh the screen

I need help figuring out how to update my PHP webpage or table automatically in real-time without requiring a manual refresh. The current functionality of the page is working perfectly fine. Specifically, I want the page to instantly display any new user ...

Don't initiate the next fetch until the previous one has completed

I am currently working on sending a list of data to Google Cloud. The code I have been using is as follows: const teams = ['LFC', 'MUFC', 'CFC']; teams.forEach(team => { fetch({ url: URL, method: 'PUT ...

Creating a Authentic Screw Top Appearance with CSS

I am striving to create a realistic screw head. Here is what I have done so far: <div class="screw"><div class="indent"></div></div> .screw { position: absolute; top: 10px; left: 49%; width: 30px; height: 30px ...

Update the code from a template engine to Next.js

I have a .pug app and I want to convert it to a next app. My current app uses the .pug engine, but I know that Next.js is different. How can I go about converting my app to Next.js? Currently, my files are in the views folder and within the views, the fi ...

A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json": { "job": { "id": 1, "name": "Job 1", "description": "bla bla bla", "locations": { "type": "FeatureCollection", "features": [{ "id": 1, "t ...

Utilize Angular2 with ES6 modules while running an Express server

Having some issues using ES6 Modules with Angular2 in an app served by Node.js and Express.js. When attempting to load the Angular2/ES6 app in browser, encountered this error message in the FireFox console: The stylesheet http://localhost:8080/boot.css w ...

How can I simulate an `Error` without it being displayed in the console or halting the entire file execution in JavaScript?

Is it possible to log an error and continue running the file without interruptions? I would like a way to achieve something similar to throwing an error but keep the file running smoothly like with console.log. Any suggestions on how to accomplish this? ...

Click to Resize Window with the Same Dimensions

I have a link on my website that opens a floating window containing more links when clicked. <a href='javascript:void(0);' onclick='window.open("http://mylink.html","ZenPad","width=150, height=900");' target='ZenPad'>&l ...

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

stepper vue with previous and next buttons

I am trying to create previous and next buttons in Vue, but I am struggling a bit because I am new to learning Vue. I have some methods like this.activeIndex < this.activeIndex - 1 that I need to implement. Can someone help me with how to do this? cons ...

Update the innerHTML content dynamically every 5 seconds with Vue.js

I'm working on a new website and I'd like to spice things up by changing the header text with a random word every 5 seconds. Here's the starting point: const header = document.querySelector('.header') const needs = ['jacket& ...

Transferring information between pop-up and webpage

I have developed a simple form within an ERP system that allows users to create quick support tickets. However, instead of manually inputting the client ID in the form, I want to provide them with a more user-friendly option. My idea is to include a search ...