Skip to main content

Across multiple javascript projects, we use the @cognite/sdk. We observe some strange behaviour when it comes to authentication and see the Chrome network panel full of HTTP 401 calls. When debugging the issue, we see that the getToken method supplied to the CogniteClient class only gets called some times. And when it does, the code on our part successfully retrieves a valid token. This leads to some unwanted behaviour and the user sometimes needs to refresh the browser in order to correct the browser state.

I suspect the fact that we make a new instance of CogniteClient everytime we use it could be the culprit. I read from the source code baseCogniteClient.ts that the getToken function is not called each time in order to “To prevent calling `getToken` method multiple times in parallel”. Not that I am really able to follow this behaviour over multiple instances of the client.

Any pointers as to what might cause this problem?

const getToken = async () => {
  // this code only hits some times
};

const client = new CogniteClient({
appId: 'YOUR APPLICATION NAME',
project,
getToken,
});

 

Hi @Anders Nygaard,

One of the maintainers of the SDK here 👋

The getToken method will be called when:

  1. The API returns 401
  2. Someone calls `client.authenticate`

However, if multiple requests returns 401, then only a single call to `getToken` will be invoked, and all the requests will pause (not resolve it’s Promise), wait for the single `getToken` call to resolve, and then retry all the 401 requests with the new token.
 

There are some gotchas:

  1. This behavior only works inside a single SDK instance. We don’t coordinate across multiple SDK instances.
  2. We will not retry the requests if the `getToken` returns the same token used when getting 401s.

I don’t know your exact use-case, but I hope this clarifies some of the confusion.


Reply