0
0
Svelteframework~5 mins

Server load functions (+page.server.js) in Svelte

Choose your learning style9 modes available
Introduction

Server load functions let you get data on the server before showing a page. This helps keep your app fast and secure.

When you want to fetch data from a database before showing a page.
When you need to keep secrets like API keys safe on the server.
When you want to do work that should not run in the browser.
When you want to prepare data for a page before the user sees it.
Syntax
Svelte
export async function load(event) {
  // get data here
  return {
    props: {
      key: value
    }
  };
}

The load function runs only on the server in +page.server.js.

You return an object with props that become available to your page.

Examples
Simple load function returning a message to the page.
Svelte
export async function load() {
  return {
    props: {
      message: 'Hello from server'
    }
  };
}
Load function using URL parameters to fetch data.
Svelte
export async function load({ params }) {
  const id = params.id;
  const data = await fetchDataById(id);
  return {
    props: { data }
  };
}
Sample Program

This example shows a server load function that gets the current time on the server. The time is sent as a prop to the page and displayed.

Svelte
// +page.server.js
export async function load() {
  const time = new Date().toLocaleTimeString();
  return {
    props: {
      serverTime: time
    }
  };
}

// +page.svelte
<script>
  export let serverTime;
</script>

<h1>Current Server Time</h1>
<p>The time on the server is: {serverTime}</p>
OutputSuccess
Important Notes

Server load functions run only on the server, so you can safely use secrets or server-only APIs.

Returned props are merged into the page component's props automatically.

If you want to load data on the client too, use +page.js load functions instead.

Summary

Server load functions run on the server before the page loads.

They help fetch data safely and prepare it for the page.

Use +page.server.js to keep code server-only.