Svelte logo

SvelteKit by Example: Page Scripts

Page scripts allow data to be fetched or prepared before the page component is rendered. When a SvelteKit app is first visited, page scripts run on the server for the initial render. On subsequent visits, page scripts only run on the client.

In this example, we'll pass an array of todos retrieved from an API to a page component.

Export a load function from a +page.js script to prepare or fetch data for the page component. Load functions may be async functions.

Data from the page script is passed to a data props on the page component.

src/routes/lists/+page.js
import { fetchLists } from './api.js';

export async function load() {
  return {
    lists: await fetchLists(),
  };
}
src/routes/lists/+page.svelte
<script>
  export let data;
</script>

<h1>Lists</h1>
<ul>
  {#each data.lists as list}
    <li>
      <a href={`/lists/${list.id}`}>
        {list.name}
      </a>
    </li>
  {/each}
</ul>

The load function receives a context argument to access route parameters and other data.

Page scripts can throw errors and modify the HTTP response code.

src/routes/[page]/+page.js
import pages from "./pages.json";
import { error } from '@sveltejs/kit';

export function load({ params }) {
  const page = pages
    .find((page) => page.slug === params.page);

  if (! page) {
    throw error(404, 'Page not found');
  }

  return { page };
}

The load function can be typed with JSDoc or TypeScript.

The data prop too.

/** @type {import('./$types').PageLoad} */
export function load({ params }) {
  // …
}
import type { PageLoad } from "./$types";

export function load({ params }: PageLoad) {
  // …
}
<script>
  /** @type {import('./$types').PageData} */
  export let data;
</script>
<script lang="ts">
  import type { PageData } from "./$types";

  export let data: PageData;
</script>