0
0
Svelteframework~5 mins

Layout load functions in Svelte

Choose your learning style9 modes available
Introduction

Layout load functions help you get data before showing a page layout. This makes sure your page has what it needs right away.

When you want to fetch user info once and use it on many pages.
When you need to load settings or theme data for the whole app layout.
When you want to show a loading state while data is being fetched for the layout.
When you want to share data between nested pages without refetching.
When you want to protect routes by checking user login status before showing the layout.
Syntax
Svelte
export async function load({ fetch, params, url }) {
  // fetch or prepare data here
  return {
    key: value
  };
}

The load function runs before the layout renders.

It returns an object whose properties become available in the layout component.

Examples
Simple load function returning a title prop for the layout.
Svelte
export async function load() {
  return {
    title: 'Welcome to My Site'
  };
}
Load function fetching user data from an API to pass to the layout.
Svelte
export async function load({ fetch }) {
  const res = await fetch('/api/user');
  const user = await res.json();
  return {
    user
  };
}
Load function reading query parameter to set language prop.
Svelte
export async function load({ url }) {
  const lang = url.searchParams.get('lang') || 'en';
  return {
    lang
  };
}
Sample Program

This example shows a load function in +layout.js providing a greeting message to +layout.svelte before rendering. The greeting is shown in the header.

Svelte
<!-- +layout.js -->
export async function load() {
  return {
    greeting: 'Hello from layout load!'
  };
}

<!-- +layout.svelte -->
<script>
  export let data;
</script>

<header>
  <h1>{data.greeting}</h1>
</header>

<slot />
OutputSuccess
Important Notes

Layout load functions run on both server and client during navigation.

Returned properties are reactive and update the layout when changed.

Use fetch inside load to get data safely with SvelteKit's routing.

Summary

Layout load functions fetch or prepare data before the layout shows.

They return an object whose properties the layout component can use.

This helps share data across pages and improve user experience.