I appologise for the way the question is phrased.
I have this server component called auth.ts that retrieves some user details after they’ve logged in.
This is my server side component //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,
//We return "id" instead of "_id" to be consistent with
//the way lucia returns the user object.
//aternatively, don't return profile id at all
//depending on the requirements of the app
_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 retrieve the data in a server component seems straightforward, I did something like this
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>
</>
)
}
</>
Tried to apply the same logic in a client component and all hell broke loose, I’ve been struggling to find a solution for a long time.
Please can someone explain what to do so that I can learn and take note of it for future references. Thanks in advance