localStorage problem in apollo authorization header in NextJS and React

Viewed 1250

I use this solution to use apollo client in my NextJS and React project.

Why I can't use localStorage in withApollo.js?

I run this code:

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

export default withApollo(
  ({ initialState }) => {
    return new ApolloClient({
      uri: 'http://localhost:8000/graphql/',
      cache: new InMemoryCache().restore(initialState || {}),
      headers: {
        authorization: localStorage.getItem("token")
      }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} />
        </ApolloProvider>
      );
    }
  }
);

and I see this error:

ReferenceError: localStorage is not defined
module.exports../lib/withApollo.js.__webpack_exports__.default.next_with_apollo__WEBPACK_IMPORTED_MODULE_1___default.render.Page.Page ./lib/withApollo.js:11

Can you help me?

0 Answers
Related