I am using +layout.server.ts
to redirect unauthenticated users from accessing authorized routes with this code:
/* +layout.server.ts */
export const load: PageServerLoad = async () => {
// ...
if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {
throw redirect(300, "/sign-in");
}
}
But when I tested it by accessing an authorized url (let's say /user/profile
), the browser gave me this error:
I didn't know what was the problem. After some workarounds and debugging, I found out the error was caused by server-side rendering. Because when I turned off the SSR in +layout.server.ts
, redirect worked as expected and browser didn't throw any error. To confirm it, I also tried disabling SSR for a single page and only that page was redirecting rightly.
Why is this happening? I want to use redirect()
without disabling SSR.
UPDATE: I also tried redirect() in +page.ts
, +page.server.ts
and +layout.ts
. The same error also happened there when ssr was enabled. I don't think my client-side js code is responsible.
+page.ts
,+page.server.ts
and+layout.ts
. But it doesn't work without disabling SSR. It is bothering me so much. – Trejothrow redirect(...)
, which is throwing an error. SvelteKit catches that error and handles the redirect, but if you catch the error in a try/catch block then SvelteKit can't handle it. See the note in the docs – Freewheel