next-with-apollo
next-with-apollo copied to clipboard
Setting Headers (Auth)
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.
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>
);
}
}
);