Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SvelteKit: how can I add global error 401 handling?

Tags:

sveltekit

How can you globally handle 401 errors that come from an external API?

First of all, my setup:

  1. When the user logs in I set a jwt cookie, write a jwt property to the session store (from $app/stores), and redirect to the protected portion of the website.
  2. In hooks.js I have a handle function that basically does request.locals.jwt = cookies.jwt, and then a getSession function that returns { jwt: locals.jwt }
  3. On every fetch request that I make on the protected pages, I access and use session.jwt to send the token to the API.

That whole setup works. If the user logs out, I can just write an empty JWT cookie and clear the $session.jwt value, redirect back to the home page, done.

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 __error.svelte seemed like the obvious place but if the error is triggered during SSR, then obviously I can't do anything with cookies, and __error.svelte isn't run a second time where browser is true.

like image 735
Kevin Renskers Avatar asked Sep 16 '25 01:09

Kevin Renskers


2 Answers

Perhaps you can throw and then catch on the window object?

https://svelte.dev/repl/c6dddc73cbdd4f81883add43f5e3aa25?version=3.18.2

like image 145
anakha Avatar answered Sep 17 '25 18:09

anakha


Suggestion: Use HTTP-only cookies for your token (optional, but could be better)

in __layout.svelte, we have

<script lang="ts" context="module">
  import { isPublic, isAuthenticated } from '$lib/auth/auth0_front';
  import type { Load } from '@sveltejs/kit';

  export const load: Load = async ({ page, session }) => {
    if (!isPublic(page.path) && !isAuthenticated(session)) {
      console.log('Unauthorized access to private page');
      return { redirect: '/', status: 302 };
    } else {
      console.log('Auth OK');
    }
    return {};
  };
</script>

And on front-end side we use a small wrapper around native fetch, that handle the 401 responses by redirecting the page to the homepage or login page.

like image 20
ashas Avatar answered Sep 17 '25 19:09

ashas