SvelteKit SPA + Capacitor: a page load that calls an authed API 401s on cold load unless it awaits parent()
@sveltejs/kit 2.70 (adapter-static, ssr off, svelte 4.2) wrapped in @capacitor/core 8.5. The root +layout.ts reads the stored Bearer token and configures the generated API client (sets default Authorization header) before returning the user. A page like /lists has its own +page.ts that calls the API through that client. Navigating to it client-side works, but a cold full-page load of /lists (deep link, reload, first open) answered 401 from the API and the page showed the 502/"couldn't load" error state, while /home, loaded the same way, worked every time. Console showed two 'Failed to load resource: the server responded with a status of 401 (Unauthorized)' lines and the page's own 'lists: load failed: 401' log. The intermediate (app)/+layout.ts already does const { user } = await parent() and redirects when signed out, so I assumed the child page load could not run before the root layout had finished. Adding retries or checking the token in localStorage didn't help: the token was stored; the request simply went out without it.
Root cause: SvelteKit runs a page's load concurrently with its layouts' loads unless the page load itself calls await parent(). A sibling layout awaiting parent() does not serialize the page load after the root layout; only the page's own await parent() does. So on a cold load the page's API call fires before the root layout's load has put the Bearer on the SDK defaults, and goes out unauthenticated. On client-side navigation the root layout load has already run (its data is cached), which is why in-app navigation worked and only cold loads failed. The page that worked (/home) happened to call await parent() first.
Fix: in every universal +page.ts whose request depends on something the root layout sets up at runtime (auth header, SDK base URL, feature flags), await the parent before the first call:
export const load: PageLoad = async ({ params, parent }) => {
// Root layout's load configures the API client's Bearer; a load that
// runs beside it goes out signed out on a cold page load.
await parent();
const res = await getThingApi({ id: params.id });
...
};The cost on SSR/web is that the page load serializes after the layout chain (one extra hop); on the SPA/Capacitor side it is the only correct ordering. Documented at https://svelte.dev/docs/kit/load#Using-parent-data ("Take care not to introduce waterfalls when using await parent()") but the docs frame it as a performance warning, not as an ordering guarantee you may need. Verified with @sveltejs/kit 2.70.3, svelte 4.2.19, @capacitor/core 8.5.3.