next-apollo-ssr icon indicating copy to clipboard operation
next-apollo-ssr copied to clipboard

SSR calls don't forward cookies from the request

Open dlbnco opened this issue 1 year ago • 0 comments

In the event that the browser has cookies that are relevant to the requests made by Apollo, they should be included by the client that is run on the server-side.

This can easily be achieved by modifying the getApolloClient() function to receive an optional cookies string:

export function getApolloClient(
  forceNew: boolean,
  cookie?: string,
): ApolloClientType {
  if (!CLIENT || forceNew) {
    CLIENT = new ApolloClient({
      ssrMode: isServer,
      uri,
      cache: new InMemoryCache().restore(windowApolloState || {}),
      credentials: 'include',
      headers: {
        Cookie: cookie ?? '',
      },
    });
  }
  return CLIENT;
}

Then, on _document.tsx, just pass the cookie from the context when getting the client:

const apolloClient = getApolloClient(true, ctx.req?.headers.cookie);

I can make a pull request later :)

dlbnco avatar Jul 04 '23 19:07 dlbnco