Replies: 2 comments 2 replies
-
Beta Was this translation helpful? Give feedback.
-
|
Good question. You should not use Why
|
| Approach | Auth API calls per request | Waterfall |
|---|---|---|
safeGetSession() in each load |
1 (cached) | No — parallel |
await parent() in page load |
1 | Yes — sequential |
Both make the same number of Supabase API calls, but parent() is slower due to the waterfall.
When await parent() is fine
If you only need the session for UI rendering (not for gating access), you can use parent() in +page.ts (not +page.server.ts):
// +page.ts (universal load — runs on client too)
export const load: PageLoad = async ({ parent }) => {
const { session } = await parent();
// Use session for UI state, not for authorization
return { isLoggedIn: !!session };
};When you MUST use safeGetSession()
Any time you're making a security decision (redirect if not authenticated, fetching user-specific data from DB):
// +page.server.ts
export const load: PageServerLoad = async ({ locals: { supabase, safeGetSession } }) => {
const { session, user } = await safeGetSession();
if (!session) redirect(303, "/login");
// Safe to use user.id for DB queries
const { data } = await supabase
.from("profiles")
.select("*")
.eq("id", user.id)
.single();
return { profile: data };
};TL;DR
Call safeGetSession() in every +page.server.ts that needs auth. It's cached per-request (zero extra API calls), avoids waterfalls, and is the secure pattern because it validates the JWT server-side every time rather than trusting cached client data.
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In the docs here on building a user management app with SvelteKit, the user's session is verified from the root
+layout.server.tswhich makes the session data available to all child pages:Then in the PageServerLoad function of child routes, the session is retrieved again using
safeGetSession:Why not use the session returned from the root level
+layout.server.tsusingconst { session } = await parent();in the child routes instead of callingsafeGetSession()again? Is it necessary to callsafeGetSession()in all child routes? Is there a risk of stale session data and error states?Thanks!
Beta Was this translation helpful? Give feedback.
All reactions