Page load functions help you get data or do setup work before a page shows. This makes sure the page has what it needs right away.
0
0
Page load functions (+page.js) in Svelte
Introduction
You want to fetch data from a server before showing the page.
You need to check if a user is logged in before loading the page.
You want to prepare some settings or variables before the page appears.
You want to redirect the user to another page based on some condition.
You want to load content dynamically based on the page URL.
Syntax
Svelte
export async function load({ params, fetch, url, session }) { // your code here return { /* data for the page's `data` prop */ }; }
The load function runs before the page shows.
You return an object whose properties are available on the page's data prop.
Examples
Simple load function that sends a message to the page.
Svelte
export async function load() { return { message: 'Hello!' }; }
Load function using URL parameters to send data.
Svelte
export async function load({ params }) { const id = params.id; return { id }; }
Load function fetching data from an API before page shows.
Svelte
export async function load({ fetch }) { const res = await fetch('/api/data'); const data = await res.json(); return { data }; }
Sample Program
This example fetches a todo item before the page loads. The data is passed via the data prop and shown on the page.
Svelte
/* +page.js */ export async function load({ fetch }) { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const todo = await response.json(); return { todo }; } /* +page.svelte */ <script> export let data; </script> <h1>Todo Item</h1> <p><strong>ID:</strong> {data.todo.id}</p> <p><strong>Title:</strong> {data.todo.title}</p> <p><strong>Completed:</strong> {data.todo.completed ? 'Yes' : 'No'}</p>
OutputSuccess
Important Notes
The load function runs on the server during the first page load and on the client for navigation.
Always return an object whose properties will be available on the data prop to pass data to your page component.
Use fetch inside load to get data safely with the same origin.
Summary
Page load functions run before the page appears to get data or do setup.
They return a data object whose properties are available on the page component's data prop.
Use them to fetch data, check user state, or redirect before showing the page.