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?
2
Answers
How are these files structured? You mentioned the first one is a server component where you can retrieve the cookies and pass it to the other file, but where is the
api.ts
and what is it? Isn’t it a server component then?What is the problem with passing the cookies to that api thing? Why can’t it be a server action itself? Please provide a codesandbox with the code so we can get better overview of what you are trying to do?