Next.js Discord

Discord Forum

How to handle cookie forwarding in SSR fetch?

Unanswered
Pachon Navarro posted this in #help-forum
Open in Discord
Pachon NavarroOP
Hey, this is my first time playing with RSC in Next.js and I would like to know if there is some way how to handle SSR fetch with single fetch utility without the need of attaching the cookie header?

I created some simple demo how could I solve it, but not 100% sure if this is efficient.

Scope of problem is that I have generated fetch call that can be called on server during first load and the client sided if the query is refetched, etc., so I need to have one fetch.

const universalFetch = async (url: string) => {
  const isServer = typeof window === 'undefined';

  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };

  if (isServer) {
    const { cookies } = await import('next/headers');

    headers['Cookie'] = (await cookies()).toString();
  }

  return fetch(url, {
    method: 'GET',
    headers,
    credentials: 'include',
  }).then(res => res.json());
};

1 Reply

Western paper wasp
hi. on the server, you need to read cookies via cookies() from next/headers and explicitly pass them into fetch. There is no universal “automatic” way without headers. For RSC, this is the recommended pattern.