如何解决使用 Apollo Client 和 Next-Auth 从 cookie 中获取令牌
你能帮我检查一下我的代码是否可以从 cookie 中获取访问令牌并通过 apollo 客户端发送它?在我的 Next.js 项目中,我使用 NextAuth 进行身份验证。用户登录后,我在会话中保存用户信息和访问令牌。但我知道如何获取它并将其传递给 apollo 客户端。
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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。