Svelte logo

SvelteKit by Example: Server Scripts

Server scripts also fetch or prepare data before the page component is rendered. Unlike universal page scripts, they never run in the browser. Client-side navigation asks the server for their data when needed; hydration reuses the initial data.

A prerendered page runs its server load function at build time. Reading a database on each visit needs a server runtime and a server adapter, unlike this static documentation site. Don't prerender a page whose data needs to stay fresh on each request.

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

Export load from +page.server.js. The database helper is a placeholder for your own server-only module, returning lists with id and name fields.

src/routes/lists/+page.server.js
import { getListsFromDatabase } from '#lib/server/db.js';

/** @type {import('./$types').PageServerLoad} */
export async function load() {
  return {
    lists: await getListsFromDatabase(),
  };
}

The returned data is passed to the page's data prop. Only return data that is safe to send to the browser.

src/routes/lists/+page.svelte
<script>
  /** @type {import('./$types').PageProps} */
  let { data } = $props();
</script>

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