Route protection at page level in async svelte + ssr #16243
|
I tried using this helper: export async function requireAuth() {
const session = await getCurrentSessionQuery();
if (!session) {
throw redirect(302, "/signin");
}
return session;
}in <script lang="ts">
import { requireAuth } from "@/helpers/require";
const session = await requireAuth();
</script>
<pre>{JSON.stringify(session, null, 2)}</pre>Is this okey or should I stick to protecting routes using |
Replies: 2 comments 2 replies
|
Stick with the server side, but don't reach for
You don't need the if/else hell to avoid the component approach though. The helper you already wrote works as-is in a // +page.server.ts
export const load = async (event) => {
const session = await requireAuth(event); // throws redirect(302, '/signin') when there's no session
return { session };
};One line per protected route, redirect fires reliably because |
|
An auth helper like this might not be reliable when combined with other loading mechanisms (which could happen as separate requests that will not be intercepted). It might be OK as a remote function, as those should all be executed together on the server before returning when using remote functions exclusively. Though with remote functions, those should be protected on their own to prevent bypasses, so you probably would not call the utility directly but have each remote functions call it. (Because there can be many such functions, I opened an issue about module-level protection a while ago.) If you are not going with remote functions, you probably should still stick to |
An auth helper like this might not be reliable when combined with other loading mechanisms (which could happen as separate requests that will not be intercepted).
It might be OK as a remote function, as those should all be executed together on the server before returning when using remote functions exclusively. Though with remote functions, those should be protected on their own to prevent bypasses, so you probably would not call the utility directly but have each remote functions call it. (Because there can be many such functions, I opened an issue about module-level protection a while ago.)
If you are not going with remote functions, you probably should still stick to
hooks.server.tsto…