Refetch access token after callback

I’m using auth-0/react SDK for the Gatsby app, as I need dynamic callback URLs I created a callback page stored the redirect URL in local storage, and forwarded the key to auth0 for authorization as mentioned here (PS: I’m storing the access token to local storage for further usage). It’s working well, but now I’m facing an issue where if the token is expired there is no way to get a new token without calling getAccessTokenSilently from the code as my backend needs to verify the token. But doing that raises the issue where some of the backend calls are fired even before the new token is being set in local storage. Any possible way to improve in this part?

Hi @DawnMD,

Welcome back to the Auth0 Community!

You shouldn’t be storing the access token in local storage. The getAccessTokenSilently method has an automatic caching mechanism. It will store the token and fetch a new one when needed.

Let me know if you have any questions.

In my particular scenario I’m using the token in a backend request with acxios. And I’m sending the token using axios interceptors where I cannot call any hooks or getAccessTokenSilently. So how can I deal with that situation?

I think you should still be able to set up an interceptor to use a token. Do you have any code snippets you can share to see what you’re working on?

Sure. Currently I’m setting the token in localStorage then setting it in the interceptor:

const instance = axios.create({
  baseURL: process.env.GATSBY_API_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

const getCurrentCurrency = () => loadState(CURRENCY) || IDR;

instance.interceptors.request.use(
  async function (config) {
    const jwt =
      isTokenValid(GUEST_SERVICE_TOKEN) && loadState(GUEST_SERVICE_TOKEN);
    if (jwt) {
      config.headers.Authorization = `Bearer ${jwt}`;
    }
    config.headers.AUTH_TOKEN = getOrSetSessionId();
    config.headers.LOCALE = getCurrentLanguage();
    config.headers.CURRENCY = getCurrentCurrency();
    config.headers.COOKIESENABLED = isCookieEnabled();
    config.headers.APPVERSION = process.env.GATSBY_COMMIT_REF;

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

Could you do something like this:

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