title: SvelteKit: how can I add global error 401 handling?
body: <p>How can you globally handle 401 errors that come from <strong>an external</strong> API?</p>
  <p>First of all, my setup:</p>
  <ol>
  <li>When the user logs in I set a <code>jwt</code> cookie, write a <code>jwt</code> property to the <code>session</code> store (from <code>$app/stores</code>), and redirect to the protected portion of the website.</li>
  <li>In <code>hooks.js</code> I have a <code>handle</code> function that basically does <code>request.locals.jwt = cookies.jwt</code>, and then a <code>getSession</code> function that returns <code>{ jwt: locals.jwt }</code></li>
  <li>On every <code>fetch</code> request that I make on the protected pages, I access and use <code>session.jwt</code> to send the token to the API.</li>
  </ol>
  <p>That whole setup works. If the user logs out, I can just write an empty JWT cookie and clear the <code>$session.jwt</code> value, redirect back to the home page, done.</p>
  <p>But I see no way to add a global 401 handler? What I want to do is clear the JWT cookie and redirect to the login page. Doing it in the root <code>__error.svelte</code> seemed like the obvious place but if the error is triggered during SSR, then obviously I can't do anything with cookies, and <code>__error.svelte</code> isn't run a second time where <code>browser</code> is <code>true</code>.</p>