Next.js 使用Apollo客户端和下一次身份验证从cookie获取令牌

Next.js 使用Apollo客户端和下一次身份验证从cookie获取令牌,next.js,apollo-client,next-auth,Next.js,Apollo Client,Next Auth,你能帮我检查一下我的代码吗?我是否可以从cookie中获取访问令牌并通过apollo客户端发送?在我的下一个.js项目中,我使用NextAuth进行身份验证。用户登录后,我将用户信息和访问令牌保存在会话中。但我知道怎么才能拿到它,并把它交给阿波罗的客户 import { useMemo } from 'react' import { ApolloClient, ApolloLink, InMemoryCache, createHttpLink } from '@apollo/client' im

你能帮我检查一下我的代码吗?我是否可以从cookie中获取访问令牌并通过apollo客户端发送?在我的下一个.js项目中,我使用NextAuth进行身份验证。用户登录后,我将用户信息和访问令牌保存在会话中。但我知道怎么才能拿到它,并把它交给阿波罗的客户

import { useMemo } from 'react'
import { ApolloClient, ApolloLink, InMemoryCache, createHttpLink } from '@apollo/client'
import { setContext } from '@apollo/client/link/context';
import { concatPagination } from '@apollo/client/utilities'
import merge from 'deepmerge'
import isEqual from 'lodash/isEqual'

export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'

let apolloClient

const CLIENT_URL =
  process.env.NODE_ENV === 'production'
    ? process.env.API_END_POINT
    : 'http://localhost:1337'

function createApolloClient() {
  const httpLink = createHttpLink({
    uri: `${CLIENT_URL}/graphql`,
    credentials: 'same-origin'
  });

  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : ''
      }
    }
  });

  const cache = new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          jobs: concatPagination(),
        },
      },
    },
  });

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

  return client;

}

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) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract()

    // Merge the existing cache into data passed from getStaticProps/getServerSideProps
    const data = merge(initialState, existingCache, {
      // combine arrays using object equality (like in sets)
      arrayMerge: (destinationArray, sourceArray) => [
        ...sourceArray,
        ...destinationArray.filter((d) =>
          sourceArray.every((s) => !isEqual(d, s))
        ),
      ],
    })

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data)
  }
  // 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 addApolloState(client, pageProps) {
  if (pageProps?.props) {
    pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
  }

  return pageProps
}

export function useApollo(pageProps) {
  const state = pageProps[APOLLO_STATE_PROP_NAME]
  const store = useMemo(() => initializeApollo(state), [state])
  return store
}

你能不能修改你的
useAppollo
函数以期望得到一个cookie,然后在调用时传递它?@juliomalves你能给我一个示例吗?我是GraphQL新手,您可以使用任何库,如
universal cookies
,并执行
new cookies()
(基本上就像您在任何基于React的应用程序中所做的那样)。客户端,这将从浏览器获取cookies。请澄清此处的上下文(客户端或服务器渲染)好吗?因为服务器端您可以从请求中获取cookie并将其作为参数传递,所以这有点复杂,但不多。hi@EricBurel it client-side。它将从浏览器中获取cookie。因此,是的,您可以像往常一样使用普通浏览器API获取cookie: