I’ve a react app and want to get a Bearer Token inside a TypeScript component
When I use the following code useAuth0() is only allowed inside a react hook.
That is correct. React allows calling a hook only from a React component or from another hook.
There are few approaches you can take.
Use useAuth0 hook in every React component that needs to make an API call to de-structure getAccessTokenSilently. And use it to obtain the access token. And then pass it to the API call as an argument. With this approach, you will be required to modify the API signatures to accept accessToken argument.
A slight improvement to approach 1 is, creating an AuthProvider component that wraps your app. The AuthProvider calls getAccessTokenSilently to obtain the accessToken and then provides it to the children components. The children components use the provided accessToken and pass it to the API. This still requires you to modify the API signatures to accept access Token but it avoids calling useAuth0 in every component that calls an API.
Similar to approach 2, you can create an AuthProvider that obtains the accessToken once. But instead of providing it to the children, it calls an API provided by your API library to set the accessToken globally. This accessToken can be used by all the API calls in the library. I’m currently trying this option out myself.
Hi @support12, Thanks for explaining the 4 approaches. Currently we are struggling to implement this solution. Is it possible to provide some git reference or some sample code for approach 2 and 4.
@evan.gillogley I just recently implemented something for this and wrote about it Maffin Blog - Next.js feature flags with auth0 (full example of retrieving access token with roles and injecting it to a class to it can be used in the server actions). The snippet:
export default class AccessTokenHolder {
static _accessToken: string;
static get accessToken() {
return Actions._accessToken;
}
static set accessToken(token: string) {
Actions._accessToken = token;
}
}