I am developing a web app where I need to pass session?.user?.email
from useSession()
in next-auth/react
to a sever side component where it carries out a fetch request to /api/users/email/
to find out if a user exists with that particular email address.
After reading the documentation, I realised that you are not supposed to use server components inside 'use client'
components where I have my useSession()
What is the best way to structure this?
You can use getServerSession
method to get it on server component directly:
export default async function ServerComponent() {
const session = getServerSession(authOptions) // auth options you defined somewhere to consume with handler
return <> {session?.user.email} </>
}
I suppose using useSession on client makes additional requests as stated here link: Due to the way Next.js handles getServerSideProps and getInitialProps, every protected page load has to make a server-side request to check if the session is valid and then generate the requested page (SSR). This increases server load, and if you are good with making the requests from the client, there is an alternative. You can use useSession in a way that makes sure you always have a valid session. If after the initial loading state there was no session found, you can define the appropriate action to respond.
So maybe reconsider getting it on server and then passing to client when needed