How can you globally handle 401 errors that come from an external API?
First of all, my setup:
jwt
cookie, write a jwt
property to the session
store (from $app/stores
), and redirect to the protected portion of the website.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 }
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
.
Perhaps you can throw
and then catch on the window object?
https://svelte.dev/repl/c6dddc73cbdd4f81883add43f5e3aa25?version=3.18.2
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With