Currently, I am in the process of developing a NextJS
application and facing a challenge with accessing a cookie
to utilize it for setting a Http Header
within a GraphQL Request
. For this task, I am integrating apollo-link-context
. Below is the snippet of code responsible for creating the ApolloClient
.
function createApolloClient(initialState = {}) {
const httpLink = new HttpLink({ uri: `${baseUrl}/graphql`, credentials: 'same-origin', fetch })
const authLink = setContext((_, prevCtx) => {
let token = ''
if (typeof window === 'undefined') token = getCookieFromServer(authCookieName, REQ)
else token = getCookieFromBrowser(authCookieName)
return ({ headers: { 'Auth-Token': token } })
})
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
cache: new InMemoryCache().restore(initialState),
link: authLink.concat(httpLink)
})
return client
}
A hurdle arises as the getCookieFromServer
function requires an Express Request
as its second parameter to extract the cookie from req.headers.cookie
. At present, I am uncertain about where to procure this information.