React - Getting a token for an API call outside of a functional component

Hello Everyone,
i am using Auht0 in an react app together with Apollo Client. ApolloClient is instantiated in a wrapper which I pass to the root component. It basically looks like this:

import { ApolloLink, HttpLink } from '@apollo/client';
import {
  NextSSRApolloClient,
  ApolloNextAppProvider,
  NextSSRInMemoryCache,
  SSRMultipartLink,
} from '@apollo/experimental-nextjs-app-support/ssr';
import { loadErrorMessages, loadDevMessages } from '@apollo/client/dev';
import { setVerbosity } from 'ts-invariant';

import { withTokenLink } from './auth/getApolloAuthToken';

if (process.env.NODE_ENV === 'development') {
  setVerbosity('debug');
  loadDevMessages();
  loadErrorMessages();
}

function makeClient() {
  const httpLink = new HttpLink({
    uri: process.env.NEXT_PUBLIC_API_URL,
  });

  const link = ApolloLink.from([withTokenLink, httpLink]);

  return new NextSSRApolloClient({
    cache: new NextSSRInMemoryCache(),
    link:
      typeof window === 'undefined'
        ? ApolloLink.from([
            // in a SSR environment, if you use multipart features like
            // @defer, you need to decide how to handle these.
            // This strips all interfaces with a `@defer` directive from your queries.
            new SSRMultipartLink({
              stripDefer: true,
            }),
            link,
          ])
        : link,
  });
}

export default function ApolloWrapper({ children }) {
  return (
    <ApolloNextAppProvider makeClient={makeClient}>
      {children}
    </ApolloNextAppProvider>
  );

Now the withTokenLink is a helper function which is supposed to get an access token and add it to the Auh Header, so that every request made anywhere in the app will have a valid token to call the API.:

import { useAuth0 } from '@auth0/auth0-react';
import { ApolloLink } from '@apollo/client';

export const withTokenLink = new ApolloLink(async (operation, forward) => {
  // set audience and scope of the swyft resource server (swyft api)
  const audience = process.env.NEXT_PUBLIC_AUTH0_AUDIENCE;
  const scope = process.env.NEXT_PUBLIC_AUTH0_SCOPE;

  const { getAccessTokenSilently } = useAuth0();
  const accessToken = await getAccessTokenSilently({
    authorizationParams: { audience, scope },
  });

  operation.setContext({
    headers: {
      authorization: accessToken ? `Bearer ${accessToken}` : '',
    },
  });

  return forward(operation);
});

The problem is, that the helper function is not a functional component, so i can´t use the useAuth0 hook which has the getAccessTokenSilently method.

So my Question: Is there another way to get a token or invoke the getAccessTokenSilently function without using the useAuth0 hook?

Thx

1 Like

This looks similar to Modification to Auth0Provider in react-auth0-spa.js · GitHub.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.