我正在尝试使用 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` …Run Code Online (Sandbox Code Playgroud)