getTokenSilently returns undefined token for lots of concurrent requests

I have an API utility making all my requests from my fronted React app. It calls getTokenSilently each time I make an API request.

I have an upload to AWS functionality that works as follows:

  • upload files
  • makes entry in Mongodb for all entries (once)
  • uploads each file to aws
  • saves record that file has been uploaded (individually for each entry, when upload completes)

When I am uploading c. 25 files, the fourth step fails because the JWT from getTokenSilently comes through as undefined.

Is there a limit on the number of times I can call getTokenSilently in, say a minute? This is all on my local environment using the free Auth0 plan. I get a malformed Jwt error. A few other articles say I need to supply an audience in the Auth0Provider - which I have done. The error only comes up when I am doing c.25 uploads concurrently.

Thanks

Worth saying I have extracted getTokenSilently in my AUth0 hook as per the below, and get this error for some of the conncurrent requests:

Error: Request failed with status code 401
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)

export const getTokenSilently = async initOptions => {
  try {
    const client = await createAuth0Client(initOptions);
    const token = await client.getTokenSilently(initOptions);
    console.log(token);
    return token;
  } catch (error) {
    console.log("Failed to get token", error);
  }
};

Fixed this. The problem was that every time I was calling getTokenSilently, it was creating a new Auth0 client and therefore a new JWT.

What I did instead was add

let client

at the start of my useAuth0.js file. In Auth0Provider, I put

  useEffect(() => {
const initAuth0 = async () => {
  _initOptions = initOptions;
  // Initiate auth0 and assign it to auth0Client state
  client = await createAuth0Client(initOptions);
  setAuth0(client);

Then in getTokenSilently

export const getTokenSilently = async initOptions => {
  try {
    if (!client) client = await createAuth0Client(initOptions);
    const token = await client.getTokenSilently(initOptions);
    console.log(token);
    return token;
  } catch (error) {
    console.log("Failed to get token", error);
  }
};

So basically it is using the existing client instance if it can find it instead of creating a new one each time. It’s also massively speeded up my application :innocent: