0
0
Svelteframework~5 mins

Why load functions fetch data server-side in Svelte

Choose your learning style9 modes available
Introduction

Load functions get data on the server before showing a page. This makes pages faster and better for search engines.

When you want to show data right when the page loads without waiting.
When you need to keep some data hidden from the browser for security.
When you want search engines to see your page content easily.
When you want to reduce the work the browser has to do.
When you want to fetch data from a database or API securely.
Syntax
Svelte
export async function load({ fetch, params }) {
  const response = await fetch('/api/data');
  const data = await response.json();
  return { data };
}
The load function runs on the server before the page shows.
You can use fetch inside load to get data from APIs.
Examples
This example sends a simple message from the server to the page.
Svelte
export async function load() {
  return { message: 'Hello from server!' };
}
This example fetches user data from an API before the page loads.
Svelte
export async function load({ fetch }) {
  const res = await fetch('/api/users');
  const users = await res.json();
  return { users };
}
Sample Program

This Svelte component uses a load function to get a post from a server before showing the page. The post's title and body appear immediately when the page loads.

Svelte
<script context="module">
  export async function load({ fetch }) {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const post = await res.json();
    return { post };
  }
</script>

<script>
  export let post;
</script>

<main>
  <h1>{post.title}</h1>
  <p>{post.body}</p>
</main>
OutputSuccess
Important Notes

Load functions run only on the server, so they keep secrets safe.

Data fetched in load is ready when the page shows, so users see content faster.

Using load helps search engines read your page content easily.

Summary

Load functions get data on the server before the page shows.

This makes pages faster and better for search engines.

Use load to fetch data securely and improve user experience.