How to use a token with axios?

Hey, I would like to know how to get the accesToken to use it with axios?! I am using axios hooks to work with axios and fetch data from my API (https://github.com/simoneb/axios-hooks).

But I dont find any way how to get the auth0 token to the hook… any ideas?

Hi @gutisAlex,

It sounds like you would like to include the Access Token you receive from Auth0 as the bearer token in the Authorization requests made by Axios hooks. Is that correct?

It looks like you can include headers in the Request Config object:

const [{ data, loading, error }, refetch] = useAxios({
  url: "https://your-api-url"
  headers: {'Authorization': `bearer ${accessToken}`}
})
1 Like

yes I can do that but how do I get the accessToken before the hook will be executed?

Are you using the Auth0 React SDK? If so, you can use the useAuth0 hook to get the Access Token:

  const { getAccessTokenSilently } = useAuth0();
  const accessToken = await getAccessTokenSilently();

You can find a complete example of calling an external API in the Quickstart: Auth0 React SDK Quickstarts: Call an API

I tried that, but I couldnt get it to work… maybe because its an async function to get the token but it looks like I need the token when the axios hook is initialized… I am out of ideas here! I think I cannot use this library!

It might be helpful to take a look at the Quickstart. There is an example of getting an Access Token and using it to call an API:

useEffect(() => {
  const getUserMetadata = async () => {
    const domain = "YOUR_DOMAIN";

    try {
      const accessToken = await getAccessTokenSilently({
        audience: `https://${domain}/api/v2/`,
        scope: "read:current_user",
      });

      const userDetailsByIdUrl = `https://${domain}/api/v2/users/${user.sub}`;

      const metadataResponse = await fetch(userDetailsByIdUrl, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      });

      const { user_metadata } = await metadataResponse.json();

      setUserMetadata(user_metadata);
    } catch (e) {
      console.log(e.message);
    }
  };

  getUserMetadata();
}, []);

Also, would you happen to have some code from your app where you are getting the Access Token and sending it an API request? This might help us troubleshoot. Thank you!

ok I have put together some code how I need to use it:

export default function GroupsGrid() {
  const [pagination, setPagination] = useState({_limit: 4, _page: 1})
  const [totalCount, setTotalCount] = useState<number>(1);
  const { user } = useUser();

  const [{ data: groups, loading: isLoading, error: isError }] = useAxios({
      url: `${process.env.REACT_APP_SERVER_BASE_URL}/rest/v1/groups?userID=${user.userID}&_page=1&_limit=4`,
      headers: {'Authorization': `bearer ${accessToken}`}
    }
  )

  const handleChange = (event: React.ChangeEvent<unknown>, page: number) => {
    setPagination({ _limit: 4, _page: page })
  };

  return (
    <React.Fragment>
      {isError && <div>Error, the backend moved to the dark side.</div>}
      {isLoading ? (
        <div>Loading ...</div>
      ) : (
        <div>
          {groups.map((group: Group) => (
            <Grid item key={group.id} xs={6} sm={4} md={4}>
              <GroupCard {...group} />
            </Grid>
          ))}
        </div>
      )}
      <Grid container justify={"center"}>
        <Pagination page={pagination._page} onChange={handleChange} count={Math.ceil(totalCount / 10)} />
      </Grid>
    </React.Fragment>
  );
}

The problem I have is that I dont have the accessToken the time I need it for the hook. Eventhough when I would use useEffect and fetch it there…

The only way I can probably do it, is make my own hook and there I get the token when I make a call to my API.

Thanks for the code example!

Have you tried changing this to an async function so that you can await the accessToken before using the useAxios hook?

I am getting an error when making the component async:

TS2786: ‘GroupsGrid’ cannot be used as a JSX component. Its return type ‘Promise’ is not a valid JSX element. Type ‘Promise’ is missing the following properties from type ‘Element’: type, props, key

Ah, I see. I will try out this in my own app and see how you can implement this.

1 Like

@gutisAlex, are you using auth0-react or nextjs-auth0?

I am using auth0-react…

1 Like

Thanks for confirming. I’ve played around with this a bit and I think because useAxios is a hook, it would be challenging to use this with getAccessTokenSilently since you can’t use a hook within useEffect. You may need to use Axios alone within useEffect so that you can get the accessToken before making the request:

import React, { useEffect, useState } from "react";
import { Container, Row, Col } from "reactstrap";

import Highlight from "../components/Highlight";
import { useAuth0, withAuthenticationRequired } from "@auth0/auth0-react";
import Axios from "axios";

export const ProfileComponent = () => {
  const { user, getAccessTokenSilently } = useAuth0();
  const [groups, setGroupsData] = useState(null);

  useEffect(() => {
    const getUserMetadata = async () => {
      try {
        const accessToken = await getAccessTokenSilently();
        const groupData = await Axios.get(`https://jsonplaceholder.typicode.com/users`, {
          headers: {
            Authorization: `bearer ${accessToken}`
          }
        });
        setGroupsData(groupData);
      } catch (e) {
        console.log(e.message);
      }
    };
  
    getUserMetadata();
  }, []);

  return (
    <Container className="mb-5">
      <Row>
        <Highlight>{JSON.stringify(groups, null, 2)}</Highlight>
      </Row>
      <Row>
        <Highlight>{JSON.stringify(user, null, 2)}</Highlight>
      </Row>
    </Container>
  );
};

export default withAuthenticationRequired(ProfileComponent);

ok, thanks for your help… I am gonna try to build my own axios hook and implement the silent token in there… so long!

1 Like

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