Centrifuge + React

869 Views Asked by At

In our app we use centrifuge as a web socket connection + react. When it is time to refresh token, I use config function - onRefresh, then I receive new token and set it.

refreshHeaders: { Authorization: `Bearer ${localStorage.getItem("act")}` },
  onRefresh: async function (ctx, cb) {
    try {
      await axios
        .post(`${BASE_URL}/centrifugo/refresh`, null, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("act")}`,
          },
        })
        .then((data) => {
          centrifuge.setToken(data.token);
        });
    } catch {
      centrifuge.disconnect();
      console.log("resfresh failed 1");
    }
  },

But in ws connection I got an error - code:109, token expired What is wrong in my way?

1

There are 1 best solutions below

0
Alex Emelin On

For centrifuge-js v2.x for which this question was asked for - the solution is to call cb (passed by SDK in onRefresh arguments) instead of centrifuge.setToken when token is obtained from the backend.

centrifuge-js v3.x has slightly different API for token refresh, described here