Handling HTTP errors with JWTs

It would be nice to have a way to handle errors for http operations. I need to handle an expired JWT, delete my cookies and navigate to the login page. I couldn’t see any way to do this.

I ended up using a service worker to intercept all the requests, check for a 401 or 403 and then broadcast a log out event to the app.

// sw.js
function sendLogout() {
  const channel4Broadcast = new BroadcastChannel('channel4');
  channel4Broadcast.postMessage('logout');
}

const channel4Broadcast = new BroadcastChannel('channel4');

self.addEventListener('fetch', function (event) {
  event.respondWith(

    fetch(event.request).then(function (res) {
      if ([401, 403].includes(res.status)) {
        sendLogout();

        console.log('Fetch failed 401, 403. Logging out.', res);
      }

      return res;
    })

  );

});

In general I’m finding that there isn’t functionality to call JWT authenticated endpoint. I have to put my JWTs in localStorage in a custom function, and then pull it as a dynamic value in the header. And now I have to have a service worker to handle expired JWTs. I think this is a gap in the current HTTP integration functionality.

Thanks for the feedback; error-handling is on the way!