skip to Main Content

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


  1. 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.

    1. Make it client component and get cookies from document object using allCookies = document.cookie
    2. Or, if you are using Nextjs backend, you can access cookies directly using below code in the backend itself

    nextjs backend code for cookies

    Login or Signup to reply.
  2. 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! 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search