Sooraj
Sooraj

Reputation: 10567

Next JS:How to get the token stored in the cookie for a server side API call in Next JS

I followed the examples in Next.js repo to setup an apollo client. The code looks like this

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import withApollo from 'next-with-apollo'
import { createHttpLink } from 'apollo-link-http'
import fetch from 'isomorphic-unfetch'
import cookie from 'js-cookie'
// Update the GraphQL endpoint to any instance of GraphQL that you like
const GRAPHQL_URL = 'https://myurl.com'
const token = cookie.get('token')
const link = createHttpLink({
  fetch, 
  uri: GRAPHQL_URL,
  headers: {
    authorization: token ? `Bearer ${token}` : '',
  },
})
export default withApollo(
  ({ initialState }) =>
    new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {}),
    }),
)

For obvious reasons when I try to make a Graphql API call from the server side(in getInitialProps) it throws an error because the Bearer token is missing. I came across next-cookie that can help me fetch cookies on the server-side. But this requires the ctx variable. How can I access the context variable here - or is there another way to access the information stored in the cookie from the server side?

Upvotes: 2

Views: 5306

Answers (2)

Sooraj
Sooraj

Reputation: 10567

For anyone looking for a solution. I ended up using js-cookie on the client side and next-cookie on the server-side. Not sure if this is the best approach.

const token = cookie.get('token')

export default withApollo(
  ({ initialState, ctx }) =>
    new ApolloClient({
      link: createHttpLink({
        fetch,
        uri: GRAPHQL_URL,
        headers: {
          authorization: ctx ? `Bearer ${nextCookie(ctx).token}` : `Bearer ${token}`,
        },
      }),
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {}),
    }),
)

Upvotes: 0

iamhuynq
iamhuynq

Reputation: 5539

Try this

import nextCookie from 'next-cookies';
export default withApollo(
  ({ initialState, ctx }) => ...

  const token = nextCookie(ctx);

Upvotes: 1

Related Questions