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

Setting Headers (Auth)

Open casizzi opened this issue 4 years ago • 1 comments

This is not really an error, more guidance, I have been struggling with setting auth headers, do you have any example? It would be awesome to add one to the readme. Thanks in advance.

casizzi avatar Apr 17 '20 08:04 casizzi

I was looking for the same answer. So, I noticed that we can get the headers info following these instructions here: https://github.com/lfades/next-with-apollo#withapollo-api.

Knowing this I implemented the package universal-cookie. Which help me to load headers.cookie and to get the token (or whatever cookie info name). See below an example:

import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';
import Cookies from 'universal-cookie';

export default withApollo(
  ({ initialState, headers }) => {
    const cookies = new Cookies(!process.browser ? headers.cookie : null);

    return new ApolloClient({
      uri: 'https://mysite.com/graphql',
      cache: new InMemoryCache().restore(initialState || {}),
      headers: {
            your-header-info-name: cookies.get('your-cookie-info-name')
      }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} />
        </ApolloProvider>
      );
    }
  }
);

davidsonsns avatar Apr 25 '20 22:04 davidsonsns