I have a problem with fetching user's data to my NextJS frontend application from my backend REST API.
As I mentioned the entire application consists of separated frontend (React/NextJS 14) and backend REST API (Java/Springboot).
Authentication looks like this:
Now when the user is authenticated and session is created I want to fetch the user's data from backend. I have prepared an API endpoint /batches/{userId}
. It is necessary to add JWT in the request header (Authorization: Bearer "JWT") and userId as a URL parameter. These informations are in session.
If I want to read informations from session it's needed to use useSession()
from next-auth/react
. This function works only in client component (with 'use client').
Fetch is used with async
and await
but it's not supported in client components. So, how to solve that with best practices?
Simply put in my component I need to read informations with useSession() from session, add these informations to request and fetch data from backend. How to do that?
Thanks!
you could write an async function and call the function. since you want to do client side authentication fetching, you should be doing it inside useEffect
so you would get the information before your component mounts.
const {data:session}=useSession()
useEffect(()=>{
async function fethUserInfo(){
// send request here using session information
// add more logic
}
// call the function
fetchUserInfo()
},[add correct dependency here])