Global 401 handling #6779
Replies: 2 comments 4 replies
-
What I am basically trying to do is adding something like this to my API method (a simple wrapper around
But it simply doesn't delete the cookie, even though the endpoint is getting called. |
Beta Was this translation helpful? Give feedback.
-
I don't think this is an issue with cookies. (I'm mainly interested in that possibility, since I was recently working on that API.) As you said above, replacing the import { redirect } from "@sveltejs/kit";
import type { LayoutLoad } from "./$types";
export const load: LayoutLoad = async ({ data }) => {
if (data.token) {
// Why does a relative URL not work here???
await fetch("http://127.0.0.1:5173/auth/logout", { method: "POST" });
// throw redirect(307, "/");
return redirect(307, "/");
}
return data;
}; So, IMO, it's some inconsistency in whether you throw or return |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to globally handle 401 errors coming from my external server by clearing the token cookie, and then redirecting the user back to the homepage (just to keep it simple). The scenario is that the user has a token stored in his cookie, and this token is no longer valid. An edge case, but one that definitely needs to be handled.
This used to work fine with older versions of SvelteKit by adding the 401 detection code to my API layer: if the response code from the external request is 401 then I call a local endpoint which removes the cookie, then I redirect, and all is done. But now cookies are no longer getting removed, even though the local endpoint gets called just fine.
So instead I tried to create a simple handleError hook:
While this does delete the cookie, I can't redirect from this code so the user still sees a big fat error on his screen until he manually refreshes, which is just not very friendly of course.
Are there better ways of globally handling 401 errors? I just need to delete the cookie and redirect the user to the homepage. Keeping in mind that these 401 errors can be triggered from SSR and from client side code.
Beta Was this translation helpful? Give feedback.
All reactions