Skip to content

Lesson 5 of 9 · 26m

Server Loading and Data Flow: fetch, params, and invalid

Universal versus server load functions, serialization boundaries, invalidation, and the secrets mistakes that leak into client bundles.

The most important SvelteKit question is not "where do I fetch?" It is "which side of the trust boundary owns this data?" +page.js runs universally; +page.server.js runs only on the server. Confusing those two files is how private API keys end up in public JavaScript.

Server load for private or backend-owned data

// src/routes/incidents/[id]/+page.server.ts
import { error } from "@sveltejs/kit";
import { PRIVATE_API_TOKEN } from "$env/static/private";
export async function load({ params, fetch }) {
  const res = await fetch(`https://ops.internal/api/incidents/${params.id}`, {
    headers: { authorization: `Bearer ${PRIVATE_API_TOKEN}` },
  });
  if (res.status === 404) error(404, "Incident not found");
  if (!res.ok) error(502, "Incident service unavailable");
  return { incident: await res.json() };
}

The page receives exactly what load returns:

<script>
  let { data } = $props();
</script>

<h1>{data.incident.title}</h1>

Server load can read cookies, private environment variables, databases, and internal services. Its return value crosses the serialization boundary into HTML and client hydration, so it must be data — not database handles, functions, or class behavior.

Universal load for public or client-needed data

// src/routes/docs/[slug]/+page.ts
export async function load({ fetch, params }) {
  const res = await fetch(`/content/docs/${params.slug}.json`);
  return { doc: await res.json() };
}

Universal loaders run on the server for the first render and in the browser for client-side navigation. Use them for public data, route-level configuration, or data already available to the browser. Never import $env/static/private here.

Waterfalls and invalidation are architecture

Parent layouts load before child pages; their returned data merges downward. That can create a request waterfall. Hoist shared data into +layout.server.js only when it is genuinely shared, and use the provided fetch so SvelteKit can forward cookies and handle server-side requests correctly.

Mutation or external change? Invalidate deliberately:

import { invalidate } from "$app/navigation";
await invalidate("/api/incidents");

Or tag dependencies inside load with depends("incidents:list") and call invalidate("incidents:list") after a mutation. If you invalidate everything after every action, you have recreated the refresh-everything SPA with extra ceremony.

Field notes

  • error() throws for control flow. Do not catch it accidentally inside a broad try and turn every 404 into a 500.
  • load return values are serialized with devalue; many JavaScript values survive, but behavior and secrets do not belong there.
  • Browser fetch credentials and server fetch credentials are different environments. Use the load-function fetch argument, not naked global habit.
  • A page that flashes empty after hydration often fetched once in load and again in $effect; pick one owner.

Was this lesson helpful?

Sign in to rate