Access user's accessToken from the Apollo client

Please include the following information in your post:

  • SDK: @auth0/nextjs-auth0
  • SDK Version: latest vewsion
  • Platform Version: nextjs
  • Code Snippets :
    import { useMemo } from ‘react’;
    import { ApolloClient, HttpLink, InMemoryCache, from } from ‘@apollo/client’;

import { onError } from ‘@apollo/client/link/error’;
import { setContext } from ‘@apollo/client/link/context’;
import { concatPagination } from ‘@apollo/client/utilities’;
import merge from ‘deepmerge’;
import isEqual from ‘lodash/isEqual’;
import { getAccessToken } from ‘@auth0/nextjs-auth0’;

export const APOLLO_STATE_PROP_NAME = ‘APOLLO_STATE’;

let apolloClient;

const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}
)
)
if (networkError) console.log([Network error]: ${networkError})
});

const httpLink = new HttpLink({
uri: process.env.NX_GRAPHQL_URI || “http://localhost:4000/graphql”,
});

const authLink = setContext(async (_, { headers, req, res }) => {
const token = await getAccessToken(req, res); :point_left:

return {
headers: {
…headers,
authorization: token ? Bearer ${token} : ‘’,
}
}
})

function createApolloClient() {
let defaultOptions

if (typeof window === ‘undefined’) {
//We don’t want any cache to be stored server side
defaultOptions = {
query: {
fetchPolicy: ‘no-cache’,
errorPolicy: ‘all’,
}
}
} else {
//We immediately show results, but check in the background if any changes occured, and eventually update the view
defaultOptions = {
query: {
fetchPolicy: ‘cache-and-network’,
errorPolicy: ‘all’,
}
}
}
return new ApolloClient({
ssrMode: typeof window === ‘undefined’,
link: from([errorLink, authLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
},
},
}),
defaultOptions,
})
}

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 initialState from getStaticProps/getServerSideProps in the existing cache
const data = merge(existingCache, initialState, {
  // 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;
}

Is this a feature request or bug report? If so, please create an issue directly in the corresponding GitHub repo. The Community SDK category is for general discussion and support.

1 Like