I can get the cookies in server side components and pass them to API functions like this:
import { cookies } from 'next/headers';
const cookieStore = cookies();
const sessionId = cookieStore.get('SESSIONID.DEV')?.value;
const asset = await queryClient.fetchQuery({
queryKey: ['asset', params.id],
queryFn: () => fetchData(params.id, sessionId),
});
console.log('Fetched asset:', asset);
Then in api.ts, I have something like this (otherwise, the cookies won’t be sent in server side components, and I’ll get a 401 unauthorized error):
const api = axios.create({
baseURL: getBaseUrl(),
headers: {
Accept: 'application/hal+json',
'Content-Type': 'application/json',
},
withCredentials: true,
});
export const fetchData = async (id: string, sessionId: string) => {
try {
const response = await api.get(`/data/${id}`, {
headers: {
'Accept-Version': '0.24.0.0',
Cookie: `SESSIONID.DEV=${sessionId}`,
},
});
return response.data;
} catch (error) {
console.error('Error fetching current asset', error);
throw error;
}
};
But I don’t want to pass sessionId
to every API function, so I tried getting the cookies in my api.ts file. However, I got this error:
Invariant: cookies() expects to have requestAsyncStorage, none available.
So it seems like I can only use Next.js’ cookies in server components. How can I solve this dilemma?