getTokenSilently in State Component in React


Using auth0-spa-js 1.0.2, react 16.8.6

I am trying to set up Auth0 for an SPA and it works amazing for functional components in React.
I am however stuck when I try to make an API call in a Class Component.

This is what I use in my functional components:

import React from 'react';
import { useAuth0 } from '../react-auth0-spa';

const Profile = () => {
  const { loading, user, getTokenSilently } = useAuth0();

And this is what I tried to do in a class component:

import React from 'react';
import { useAuth0 } from '../react-auth0-spa';

class Admin extends React.Component {
  async componentDidMount() {
    const { loading, user, getTokenSilently } = useAuth0();
    try {
      const token = await getTokenSilently();

Which results in the following error:

Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See for tips about how to debug and fix this problem.

… with references to the const { loading, user, getTokenSilently } = useAuth0(); line and const token = await getTokenSilently();.

I assume this is simply because I don’t understand how to use the getTokenSilently function inside a class component, but I cannot find any documentation or guides on it, and I have been (sadly) trying to fix this same error for hours. I hope someone can give me a hand or point me in the right direction.

Thanks in advance.

1 Like

Did you found a solution for this? Because I have a similiar problem with getting a token from Auth0 spa.

async function CallApi(userId) {
  const { getTokenSilently } = useAuth0();
  const token = await getTokenSilently();
  var result = {};
  try {
    console.log("Token" + token);

    const response = await fetch(process.env.API_URL + "users", {
      headers: {
        Authorization: `Bearer ${token}`,
        user_id: userId

    result = JSON.stringify(await response.json());

  } catch (error) {
  return result;

export default CallApi;

I’m having the same issue and can’t find documentation on how to access the token with class components. Did you figure this out?

I am experiencing the same challenge!
Invalid token is being returned by getTokenSilently() ?

Hi everyone,

As mentioned here:, you can use withAuth0, which exposes the same properties and methods as useAuth0.

Here is an example to get use getAccessTokenSilently:

class YourComponent extends Component {
  async methodThatNeedsToRetrieveAToken() {
    const { getAccessTokenSilently } = this.props.auth0;
    const token = await getAccessTokenSIlently();
    // use token

export default withAuth0(YourComponent );
1 Like

Thanks for sharing that @frederik.prijck!