Next.js Discord

Discord Forum

How to pass session information from Next Auth to a separate backend?

Unanswered
Basenji posted this in #help-forum
Open in Discord
BasenjiOP
I have set up next auth v5 on my next.js, but I want to be able to pass down the session information to my separate backend (using Fastify) with each request, so I can validate it and get the user information, but I'm not sure how to do it.

Perhaps you guys have any ideas or examples? Thanks.

3 Replies

Chum salmon
What do you mean by passing session information to separated backend?
When you want to verify a user you check if there are logged in by using getServerSession from next auth.
const session = await getServerSession(authOptions);
Now you have the session information. Assuming your user session contains an email, you can retrieve it like this:
const email = session.user.email as string;
You can then use this email to compare with data from your other backend.
For example, if you want to show the delete or edit button only to the post owner, you can define a new constant isEditable:
const isEditable = email === authorEmail;
(assuming you have authorEmail for each post)
The above code will return either true or false. Then, you can use the && operator to conditionally display the Delete and Edit buttons as follows:
{ isEditable && (
                        <div className={styles.editable}>
                            <DeleteButton />
                            <EditButton />
                        </div>
                    )}
Chum salmon
BasenjiOP
Yea this I do understand, but let's say I want to make an API call to my separate backend (I'm using Fastify), how do I send over the user email in a cookie? or in a header? Keep in mind that I want to attach the cookie or the header with every incoming request from my nextjs client-side requests