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

When I attempted to POST a js::array in JSON, the response returned "undefined:undefined"

I have a javascript array on the frontend that I need to send to my Tomcat server. Currently, I am using the following code but encountering issues: console.log("preview list. postUsers()"); console.log(Ext.getCmp("preview-container").get ...

Tips for Retrieving the Key Names of JSON Objects within a JSON Array

I'm trying to retrieve the object names "channelA" and "channelB". Here is the JSON data: [ { "channelA": { "programmes": [ { "start_utc": 1522208700, "stop_utc": 152220 ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...

Why don't I need to include an onload event to execute the setInterval() method within the script tag?

Hey there! I'm diving into the world of Javascript and I've come across this interesting code that changes an image every four seconds. Surprisingly, it's working perfectly fine even though I didn't include an onload event to execute th ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

When making a request through local apache, the POST method is switched to GET

I've been attempting to send a post request using the code below. However, the request is being sent as a GET instead of POST. How can I resolve this issue? $.ajax({ url: 'https://www.exampleurl.com', method: 'POST', h ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

Is it possible to use Javascript to retrieve a variable from a remote PHP file?

I am trying to retrieve a variable from a remote PHP file using JavaScript in my phonegap application. The same origin policy doesn't apply here, so I believe I need to use JSON/AJAX for this task. However, I have been unable to find any tutorials tha ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

Switching from file:// to http:// in Angular / Ionic is a necessary step when incorporating external scripts like the Disqus directive into your project

Currently, I am attempting to incorporate the disqus directive into my project. The documentation for this directive can be found here. However, I have encountered some issues due to the particular setup of my application. There is a line in the script wh ...

What is the best way to set the active class on the initial tab that is determined dynamically rather than a static tab in Angular?

I'm currently facing a problem with ui-bootstrap's tabsets. I have one tab that is static (Other) and the rest are dynamically added using ng-repeat. The issue I'm having is that I can't seem to make the first dynamically loaded tab act ...

How can JavaScript be used to remove HTML tags from text while preserving a space between each line?

I found a helpful solution on Stack Overflow for removing HTML from text content. This is the method it suggests: function strip(html){ let doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || "&quo ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Executing HTTP Requests for Elements in an Array using JavaScript

I am currently struggling with a script that sends HTTP requests to a website in order to obtain various documents. The document IDs are stored within an array, and my intention is to send a request for each element in the array and return a unique message ...