# How to use a token with axios?

**URL:** <https://community.auth0.com/t/how-to-use-a-token-with-axios/63171>\
**Category:** Get Help\
**Created:** [May 21, 2021, 3:27pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171 "2021-05-21T15:27:05Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 21, 2021, 3:27pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/1 "2021-05-21T15:27:06Z")

</div>

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](https://github.com/simoneb/axios-hooks)).

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

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 21, 2021, 7:41pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/3 "2021-05-21T19:41:54Z")

</div>

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](https://github.com/axios/axios#request-config) object:

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

```

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 23, 2021, 2:08pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/4 "2021-05-23T14:08:48Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 24, 2021, 11:21am UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/5 "2021-05-24T11:21:39Z")

</div>

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

```auto
  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](https://auth0.com/docs/quickstart/spa/react/02-calling-an-api)

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 24, 2021, 3:09pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/6 "2021-05-24T15:09:14Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 24, 2021, 3:30pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/7 "2021-05-24T15:30:10Z")

</div>

It might be helpful to take a look at the [Quickstart](https://auth0.com/docs/quickstart/spa/react/02-calling-an-api?_ga=2.183422190.932252088.1621856610-1595415333.1607347674&_gac=1.187692250.1620663261.Cj0KCQjws-OEBhCkARIsAPhOkIbhK13acrxZIWhKyPE4GlpGf7ZKmKpxtmuQbD_VcaLmyScFgvNZcmAaAntFEALw_wcB). There is an example of getting an Access Token and using it to call an API:

```auto
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();
}, []);

```

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 24, 2021, 6:01pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/8 "2021-05-24T18:01:11Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 25, 2021, 3:33pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/9 "2021-05-25T15:33:57Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 25, 2021, 3:41pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/10 "2021-05-25T15:41:57Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 25, 2021, 3:47pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/11 "2021-05-25T15:47:05Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 25, 2021, 3:52pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/12 "2021-05-25T15:52:01Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 25, 2021, 3:59pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/13 "2021-05-25T15:59:25Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 25, 2021, 4:37pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/14 "2021-05-25T16:37:45Z")

</div>

I am using auth0-react…

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [May 25, 2021, 7:02pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/15 "2021-05-25T19:02:20Z")

</div>

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:

```auto
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);

```

---

<div class="post-metadata">

**Author:** ![gutisAlex](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gutisalex/32/14464_2.png) [@gutisAlex](https://community.auth0.com/u/gutisAlex)\
**Post date:** [May 25, 2021, 8:08pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/16 "2021-05-25T20:08:58Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [June 9, 2021, 8:09pm UTC](https://community.auth0.com/t/how-to-use-a-token-with-axios/63171/17 "2021-06-09T20:09:48Z")

</div>

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