# How to get token from outside React components?

**URL:** <https://community.auth0.com/t/how-to-get-token-from-outside-react-components/68756>\
**Category:** Get Help\
**Tags:** react, auth0\
**Created:** [August 29, 2021, 8:12am UTC](https://community.auth0.com/t/how-to-get-token-from-outside-react-components/68756 "2021-08-29T08:12:06Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![jiajun](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/jiajun/32/33256_2.png) [@jiajun](https://community.auth0.com/u/jiajun)\
**Post date:** [November 10, 2022, 9:31pm UTC](https://community.auth0.com/t/how-to-get-token-from-outside-react-components/68756/3 "2022-11-10T21:31:30Z")

</div>

Create a Interceptor class, init and export a instance

```auto
class AuthInterceptor {
  setAuthGetter(getToken) {
    this.getToken = getToken;
  }

  async intercept(config) {
    if (!this.getToken) {
      return config;
    }

    try {
      const token = await this.getToken();
      config.headers['Authorization'] = `Bearer ${token}`;
    } catch (e) {
      console.log(e);
    }
    return config;
  }
}

export const authInterceptor = new AuthInterceptor()
fetchClient.interceptors.request.use(authInterceptor.intercept)

```

Create a function component to set the getToken method

```auto
function AuthInject() {
  const { user, getAccessTokenSilently } = useAuth0();

  useEffect(() => {
    authInterceptor.setAuthGetter(getAccessTokenSilently);
    return () => authInterceptor.setAuthGetter(undefined);
  }, [getAccessTokenSilently]);

  return null;
}

//set AuthInject as children
<Auth0Provider {...auth0Config}>
  <AuthInject />
  <App />
</Auth0Provider>;

```

---

_[View the full topic](https://community.auth0.com/t/how-to-get-token-from-outside-react-components/68756)._
