ZeroSevenTen
ZeroSevenTen

Reputation: 1394

Nextjs & Apollo: Attach cookie to Apollo Client in getInitialProps server side

So I understand that I can access my cookies server side using ctx.req.headers.cookie, but I'm not sure how to send that cookie to my GraphQL endpoint with Apollo Client.

Any help? Thanks.

Upvotes: 0

Views: 2181

Answers (1)

nghiaht
nghiaht

Reputation: 795

The simplest way I can suggest is using Apollo HTTP Link's context (https://www.apollographql.com/docs/link/links/http/#passing-context-per-query)

If you monitor common HTTP requests on websites, you may notice the cookie header is set in the request headers, represent the cookies sent.

So you can send cookies to Apollo by setting the same cookie in Apollo HTTP client's headers

import {
  ApolloClient,
  InMemoryCache,
  gql,
  createHttpLink
} from "@apollo/client";


const client = new ApolloClient({
    link: createHttpLink({ uri: "https://myserver.com" })
    cache: new InMemoryCache()
  });

// Pass the cookie header into context when using ApolloClient
const cookie = 'mycookie1=myvalue1; mycookie2=myvalue2';
client.query({
      fetchPolicy: "cache-first",
      context: {
        headers: {
          cookie
        }
      },
      query: gql``
});

Or using the low-level Apollo Link: https://www.apollographql.com/docs/react/api/link/apollo-link-context/#overview

Upvotes: 8

Related Questions