[NextJs] How to get idToken in a function or in a React component?

I’m working on a NextJs app and I need to send the idToken in each backend call. Is there an easy way to implement that? Here’s our app structure (extremely simplified):
We have a React component:

/* src/pages/components/MyComponent/MyComponent.tsx */

export const MyComponent: FC<MyComponentProps> = (...) => {
  const handleClick = async () => {
    await makeBackendCall(param1, param2);
  }

  ...
  <Button onClick={handleClick} />
  ...
}

The backend call is here:

/* src/fetchers/webapi.ts */

export const makeBackendCall = (param1: string, param2: string): Promise<Response> => {
  fetch('http://some.url', {
    method: 'GET',
    headers: {
      /* *** THIS IS WHERE I NEED TO SEND idToken *** */
    }
  });
}

export const anotherCallWhichNeedsTheToken = () => {...}
export const andAnotherOne = () => {...}
/*...*/

How can I achieve this?

Hi @vtomic85,

Welcome to the Auth0 Community!

To obtain an ID token, make sure to initialize InitAuth0 with the scope=openid query parameter.

Alternatively, if necessary, you can directly pass the scope as an authorizationParams object to the ‘handleLogin’ method.

References:

Please feel free to reach out if you have any questions.

Thanks,
Rueben

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