使用 Apollo 客户端在 nextJs 中传递授权标头的最佳方法?ReferenceError:本地存储未定义

Eme*_*ine 4 javascript reactjs graphql next.js apollo-client

我正在尝试使用 nextJs 和 apollo 客户端从我的 graphql 服务器获取受保护的资源。我将授权令牌存储在客户端浏览器(本地存储)中,并尝试从 apolloClient.Js 文件中读取令牌;但它会抛出一个ReferenceError(ReferenceError:localStorage未定义)。这让我很快明白服务器端正在尝试从后端引用 localStorage;但失败了,因为它仅在客户端中可用。我的问题是,解决这个问题的最佳方法是什么?我只是在我的项目中第一次使用 apollo 客户端。我花了10多个小时试图找出这个问题的解决方案。我在网络上尝试了很多东西;没有幸运地得到解决方案。这是 apolloClient 文件中使用的代码:

import { useMemo } from 'react'
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'
import { concatPagination } from '@apollo/client/utilities'
import { GQL_URL } from '../utils/api'

let apolloClient

const authToken = localStorage.getItem('authToken') || '';

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: GQL_URL, // Server URL (must be absolute)
      credentials: 'include', // Additional fetch() options like `credentials` or `headers`
      headers: {
        Authorization: `JWT ${authToken}`
      }

    }),

    
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),
          },
        },
      },
    }),
  })
}

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient()

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    _apolloClient.cache.restore(initialState)
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient

  return _apolloClient
}

export function useApollo(initialState) {
  const store = useMemo(() => initializeApollo(initialState), [initialState])
  return store
}
Run Code Online (Sandbox Code Playgroud)

Eme*_*ine 7

仅当窗口对象不是“未定义”时,我才能通过访问本地存储来解决问题;因为它在服务器端将是“未定义”的。这会很有效,因为我们不希望服务器访问本地存储。

import { useMemo } from 'react'
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { GQL_URL } from '../utils/api'

let apolloClient

function createApolloClient() {
  // Declare variable to store authToken
  let token;
   
  const httpLink = createHttpLink({
    uri: GQL_URL,
    credentials: 'include',
  });

  const authLink = setContext((_, { headers }) => {
    // get the authentication token from local storage if it exists
    if (typeof window !== 'undefined') {
      token = localStorage.getItem('authToken');
    }
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        Authorization: token ? `JWT ${token}` : "",
      }
    }
  });

  const client = new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  });

  return client;
}
Run Code Online (Sandbox Code Playgroud)