Reputation: 301
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?
Upvotes: 1
Views: 77
Reputation: 301
This is how I solve this after doing many research and over coming trials and errors.
export const getBookInfo = async (bookCode: string) => {
const cookieList = cookies().getAll();
let pushedData: string[] = [];
cookieList.forEach((cookie) => {
if (cookie.name === 'XSRF-TOKEN') {
const val = `XSRF-TOKEN=${encodeURIComponent(cookie.value)}`;
pushedData.push(val);
}
if (cookie.name === 'laravel_session') {
const val = `laravel_session=${encodeURIComponent(cookie.value)}`;
pushedData.push(val);
}
});
const result = pushedData.join(';');
const arrayResult = result.toString();
//I make the cookies as per my requirements.
try {
const tokenCalled4PublicApis = await getPlatformToken();
const data = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/${API_ENDPOINTS.book_info}?book_code=${bookCode}`,
{
credentials: 'include',
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenCalled4PublicApis}`,
Accept: 'application/json',
Referer: `${process.env.NEXT_PUBLIC_BASE_URL}`,
Cookie: arrayResult //passed it here
}
}
);
const result = await data.json();
return result;
} catch (error) {
console.error('Error fetching platform token:', error);
throw error;
}
};
In this way, we can easily pass cookies to the backend server, if not other ways work like credentials: true etc.
Upvotes: 0
Reputation: 21
I believe you can do this. You can read the docs from HERE too.
import { cookies } from 'next/headers'
export default function Page() {
const cookieStore = cookies()
const all = cookieStore.get('XSRF-TOKEN')
... ... ...
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! :)
Upvotes: 1