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.