Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 35 ยท SvelteKit

SvelteKit Load Functions and Data Flow

Fetch data in SvelteKit with load functions - universal vs server load, params, fetch, parent data, streaming promises, invalidation, errors and redirects.

Almost every page needs data: a blog post, a product, the signed-in user. In SvelteKit you do not fetch it inside the component. You write a load function next to the page; SvelteKit runs it before the page renders, passes its result to the component as data, and on the server includes everything in the first HTML, so users and search engines get a complete page.

SvelteKit cannot run on this site, so its code is read-only here. The <TryIt> stand-ins model the data flow in plain JavaScript (a loader pipeline, with parent data, errors and invalidation) so you can run the ideas.

A first load function

JavaScript
// src/routes/blog/[slug]/+page.server.js
import { error } from '@sveltejs/kit';
import { getPost } from '$lib/server/posts';

export async function load({ params }) {
  const post = await getPost(params.slug);
  if (!post) {
    error(404, 'Post not found');
  }
  return { post };
}
HTML
<!-- src/routes/blog/[slug]/+page.svelte -->
<script>
  let { data } = $props();
</script>

<h1>{data.post.title}</h1>
{@html data.post.html}

The object returned from load becomes the data prop. Changing params.slug (clicking a link to another post) re-runs load and updates data without a full page load.

Two kinds of load

File Runs on Can use Data must be
+page.js / +layout.js (universal) server on first load, then in the browser fetch, public APIs anything, even class instances or components
+page.server.js / +layout.server.js (server) server only database, secrets, cookies, $lib/server serializable (JSON-like, plus Date, Map, Set, BigInt, Promise)

Rule of thumb: if the code touches a database, a private API key or the file system, use a server load. If it only calls a public API, a universal load saves a hop on client-side navigation. A route can have both: the server one runs first and its result is available as data to the universal one.

The load function receives an event with:

  • params: dynamic route parameters.
  • url: the URL (read url.searchParams for ?page=2).
  • fetch: an enhanced fetch that forwards cookies on the server, resolves relative URLs and avoids re-requesting during hydration. Always use this one instead of the global.
  • parent(): a function returning the parent layout's data.
  • cookies, locals, request (server load only).
  • depends('key'), setHeaders(), and more.
JavaScript
// src/routes/products/+page.js
export async function load({ fetch, url }) {
  const page = Number(url.searchParams.get('page') ?? 1);
  const res = await fetch(`/api/products?page=${page}`);
  return { page, products: await res.json() };
}

Layout data and parent

A +layout.server.js load returns data that every page below receives, merged into data:

JavaScript
// src/routes/+layout.server.js
export async function load({ locals }) {
  return { user: locals.user ?? null };
}

Every page now sees data.user. Loads for a page and its layouts run in parallel. If a page's load needs the layout's result, call await parent(), but note that it makes the page's load wait, creating a waterfall, so fetch independent data before awaiting parent().

flowchart TD
  L["+layout.server.js load -> user"] --> P["+page.server.js load -> post"]
  L --> C["+layout.svelte"]
  P --> V["+page.svelte data = user + post"]

Loads run in parallel; the page component receives the merged result.

Modelling the pipeline

This stand-in runs a layout load and a page load in parallel, merges their results and implements parent(), error() and redirect() as thrown values, which is how SvelteKit does it:

JS A load pipeline with parent(), errors and redirects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Streaming slow data

You do not have to wait for everything. Return a promise for the slow part and SvelteKit streams the page shell first:

JavaScript
export async function load({ params }) {
  return {
    post: await getPost(params.slug),   // awaited: needed for the page and SEO
    comments: getComments(params.slug), // NOT awaited: streamed in later
  };
}
HTML
{#await data.comments}
  <p>Loading comments...</p>
{:then comments}
  {#each comments as c (c.id)}<p>{c.text}</p>{/each}
{:catch}
  <p>Could not load comments.</p>
{/await}

Only stream what is not needed for the first paint or for search engines.

Errors and redirects

Inside load:

  • error(404, 'Not found') renders the nearest +error.svelte with that status.
  • redirect(303, '/login') sends the browser elsewhere (use 303 after a POST, 307/308 to keep the method).
  • Any other thrown error is a 500 and goes through the handleError hook (see Hooks and Endpoints).

Do not wrap error() or redirect() in a try/catch that swallows them; they work by throwing.

Invalidation: re-running load

load re-runs when its inputs change: a params or url value it read, or a parent it awaited. Beyond that you can trigger it yourself:

JavaScript
import { invalidate, invalidateAll } from '$app/navigation';

invalidate('/api/products');   // reruns loads that fetch this URL
invalidate('app:cart');        // reruns loads that called depends('app:cart')
invalidateAll();               // reruns every active load

A load declares a custom dependency with depends('app:cart'). After a mutation, say adding to the cart, call invalidate('app:cart') and the data updates in place.

JS Dependency tracking and invalidate()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should code that queries a private database run?

    +page.server.js runs only on the server, so secrets and database access never reach the browser. +page.js also runs in the browser during navigation.
  2. 2. What should you use inside load to make HTTP requests?

    The event's fetch forwards cookies on the server, resolves relative URLs and reuses responses during hydration.
  3. 3. How do you stream a slow comment list without blocking the page?

    Un-awaited promises in the returned object are streamed to the client when they resolve.
  4. 4. How do you make a 404 from inside load?

    The error helper from @sveltejs/kit throws a special value that renders the nearest +error.svelte with that status. A plain Error becomes a 500.

Summary

  • A load function returns the data for a page; the component reads it as data from $props().
  • Use +page.server.js for secrets and databases, +page.js for universal code; layouts share data with children.
  • Loads run in parallel; await parent() creates a waterfall, so call it last.
  • error() and redirect() work by throwing; return unawaited promises to stream slow data.
  • invalidate, invalidateAll and depends re-run loads after changes.

Next: Form Actions and Progressive Enhancement