SvelteKit Load Functions

Most pages need data before they appear, such as a list of articles or a product record. SvelteKit solves this with load functions. A load function runs before the page renders, fetches what the page needs, and hands the result to the component.

Your First Load Function

Create a +page.js file beside the +page.svelte file. Export a function named load that returns an object.

// src/routes/blog/+page.js
export async function load({ fetch }) {
  const response = await fetch("https://api.example.com/posts");
  const posts = await response.json();

  return { posts };
}

The page receives the returned object through a prop named data.

<script>
  export let data;
</script>

{#each data.posts as post (post.id)}
  <h4>{post.title}</h4>
{/each}

Use the fetch function from the load argument, not the global one. The SvelteKit version forwards cookies where appropriate and avoids duplicate requests during server rendering.

Data Flow Diagram

Visitor requests /blog
        |
        v
load() in +page.js runs
        |
        v
fetch() gets posts from the API
        |
        v
return { posts }
        |
        v
+page.svelte receives data.posts
        |
        v
Page renders with real content

Using Route Parameters

Dynamic routes pass their parameters into load. The function can fetch a single record based on the address.

// src/routes/blog/[slug]/+page.js
export async function load({ params, fetch }) {
  const response = await fetch(`/api/posts/${params.slug}`);
  const post = await response.json();

  return { post };
}

Universal Versus Server Load

A +page.js file runs on the server during the first visit and in the browser during later navigation. A +page.server.js file runs only on the server. Server-only load functions can read private keys, query databases, and use secret environment variables, because the browser never sees that code.

// src/routes/dashboard/+page.server.js
import { SECRET_API_KEY } from "$env/static/private";

export async function load({ fetch }) {
  const response = await fetch("https://api.example.com/stats", {
    headers: { Authorization: `Bearer ${SECRET_API_KEY}` }
  });

  return { stats: await response.json() };
}

Choosing The Right File

File              Runs Where               Use For
----------------  -----------------------  ---------------------------
+page.js          Server, then browser     Public data and simple calls
+page.server.js   Server only              Secrets, databases, cookies
+layout.js        Server, then browser     Data shared by many pages
+layout.server.js Server only              Shared private data

Errors And Redirects

The error helper sends a status code and a message to the nearest +error.svelte page. The redirect helper sends the visitor somewhere else. Both come from the SvelteKit package and end the load function immediately.

import { error, redirect } from "@sveltejs/kit";

export async function load({ params, fetch, locals }) {
  if (!locals.user) {
    redirect(302, "/login");
  }

  const response = await fetch(`/api/posts/${params.slug}`);

  if (response.status === 404) {
    error(404, "That post does not exist.");
  }

  return { post: await response.json() };
}

Layout Data

A layout load function supplies data to every page below it. Pages read the layout data through the same data prop, merged with their own results. A site menu or the signed-in user name fits this pattern.

Rendering Modes

SvelteKit renders the first page on the server, which helps search engines and speeds up the first view. After loading, the app takes over in the browser and handles later pages through client navigation.

A Layman Analogy

Imagine a restaurant kitchen. The load function is the prep cook who gathers and chops ingredients before the chef plates the dish. The server-only version is the locked pantry where only kitchen staff enter. Guests never see the pantry, yet they enjoy the finished meal.

Common Mistakes To Avoid

  • Putting secret keys in a +page.js file that ships to the browser
  • Using the global fetch rather than the one provided by load
  • Forgetting to return an object, which leaves data empty
  • Fetching data inside onMount when a load function would deliver it earlier

Key Points

  • Load functions fetch data before a page renders
  • Returned objects arrive in the data prop
  • Server load files keep secrets and databases private
  • Error and redirect helpers control the visitor journey