0
0
SvelteHow-ToBeginner · 3 min read

How to Use Load Function in SvelteKit: Syntax and Example

In SvelteKit, the load function runs before a page or layout renders to fetch data or perform setup. It can be exported from a page or layout script and returns data that becomes available as props in the component.
📐

Syntax

The load function is an async function exported from a +page.js or +layout.js file. It receives an object with useful properties like fetch, params, and url. It must return an object whose properties become available in the page or layout component.

  • async function load({ fetch, params, url }): The function signature with useful context.
  • return { key: value }: The data returned is passed as props to the component.
javascript
export async function load({ fetch, params, url }) {
  // fetch data or prepare props
  const response = await fetch('/api/data');
  const data = await response.json();
  return { data };
}
💻

Example

This example shows a +page.js file using load to fetch JSON data from an API endpoint. The data is then displayed in the +page.svelte component.

javascript
// +page.js
export async function load({ fetch }) {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const post = await res.json();
  return { post };
}

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

<h1>{post.title}</h1>
<p>{post.body}</p>
Output
<h1>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h1> <p>quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto</p>
⚠️

Common Pitfalls

  • Not exporting the load function will cause it not to run.
  • Returning data in the wrong format (not an object) will cause errors.
  • Using fetch incorrectly inside load can cause infinite loops if you fetch the same page URL.
  • Trying to access browser-only APIs (like window) inside load will fail because it runs on the server first.
javascript
/* Wrong: load not exported */
async function load() {
  return { data: 123 };
}

/* Right: export load */
export async function load() {
  return { data: 123 };
}
📊

Quick Reference

load function key points:

  • Runs before page or layout renders.
  • Can be async and use fetch to get data.
  • Returns an object whose properties become component props.
  • Runs on server and client during navigation.
  • Cannot use browser-only APIs directly.

Key Takeaways

Always export an async load function from +page.js or +layout.js to fetch data before rendering.
Return an object from load; its properties become props in the Svelte component.
Use the fetch provided in load to get data safely on server and client.
Avoid using browser-only APIs inside load because it runs on the server first.
Handle errors inside load to prevent page crashes during data fetching.