crispengari
crispengari

Reputation: 9333

Next.js: React Apollo Client Not sending cookies?

I'm using Apollo Client as a graphql client on my next.js application, Here is the function that creates a client for me:

let client: ApolloClient<any>;

export const __ssrMode__: boolean = typeof window === "undefined";
export const uri: string = "http://localhost:3001/graphql";

const createApolloClient = (): ApolloClient<any> => {
  return new ApolloClient({
    credentials: "include",
    ssrMode: __ssrMode__,
    link: createHttpLink({
      uri,
      credentials: "include",
    }),
    cache: new InMemoryCache(),
  });
};

Surprisingly, when I make a mutation to the graphql server I'm able to set the cookies but, I'm not able to get the cookies from the client. What may be possibily the problem?

Upvotes: 0

Views: 1789

Answers (1)

Jes&#250;spinarte
Jes&#250;spinarte

Reputation: 171

I came to the same problem, my solution was to create a client every time a server-side rendering is made, maybe it's not ideal to have a client to execute GraphQL calls in the browser and others in the server but it's what worked best for me. This is the code:

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { NextPageContext } from 'next';
import { setContext } from '@apollo/client/link/context';

export const httpLink = createHttpLink({
  uri: 'http://localhost:4000/graphql',
  credentials: 'include',
});

const CreateClient = (ctx: NextPageContext | null) => {
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        cookie:
          (typeof window === 'undefined'
            ? ctx?.req?.headers.cookie || undefined
            : undefined) || '',
      },
    };
  });

  return new ApolloClient({
    credentials: 'include',
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
    ssrMode: true,
  });
};

export default CreateClient;

So, what I do is pass the context from the getServerSideProps and see if I have some cookies there, if so I just set the cookies, you can also send the authorization token if it's in the cookie. To call it is very simple:

export async function getServerSideProps(context: NextPageContext) {
  const client = CreateClient(context);

  const { data } = await client.query({
    query: SOME_QUERY,
  });

  return {
    props: {
      data,
    },
  };
}

You can also do a HOC as in the Ben Awad tutorial Apollo Client HOC but I think it was too much for what I was trying to do. Hope it helped you or helps someone there :)

Also, I'm using Next 12.1.5 and React 18

Upvotes: 5

Related Questions