In my nextjs app, I am trying to fetch data by using async await mechanism like this
export const getHomeData = async (tokenCalled4PublicApis: string) => {
try {
// const all = getCookie('XSRF-TOKEN', { cookies });
// console.log('all cookies', all);
const data = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/${API_ENDPOINTS.HOME}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenCalled4PublicApis}`,
Accept: 'application/json',
// abc: all,
'Cache-Control':
'public, max-age=60, stale-while-revalidate=60'
},
credentials: 'include'
}
);
const result = await data.json();
return result;
} catch (error) {
console.error('Error fetching platform token:', error);
throw error;
}
};
Unfortunately not getting data, as in this way i won’t be able to pass cookies set by API. How to pass browser cookies in server-side fetch functions?
2
Answers
Give us more context about this function. Where is it written and where are you calling it? Are you handeling the backend using next.js, or using express or something?
Anyways, here are a few tricks you might try.
allCookies = document.cookie
I believe you can do this. You can read the docs from HERE too.
You can access cookies from the actual page, and you can use it wherever you want to. You may also pass it to your function like this:
getHomeData(all)
Hope it helps! 🙂