Bird
Raised Fist0
Svelteframework~3 mins

Why Page load functions (+page.js) in Svelte? - Purpose & Use Cases

Choose your learning style10 modes available
The Big Idea

Discover how to make your pages load data instantly and effortlessly every time!

The Scenario

Imagine building a website where you have to fetch data every time a page loads by writing separate code in multiple places, like inside your components or even in the browser manually.

You might have to write repeated fetch calls and handle loading states yourself, scattered all over your app.

The Problem

This manual approach is slow and messy. You risk repeating code, causing bugs, and making your app harder to maintain.

Also, fetching data inside components can cause flickering or delays because the page renders before data arrives.

The Solution

Page load functions (+page.js) let you fetch data before the page renders, keeping your code organized and efficient.

This means your page shows complete data immediately, improving user experience and making your code cleaner.

Before vs After
✗ Before
import { onMount } from 'svelte';
onMount(() => { fetch('/api/data').then(res => res.json()).then(setData) })
✓ After
export async function load() { const data = await fetch('/api/data').then(r => r.json()); return { data } }
What It Enables

It enables smooth, fast page loads with data ready upfront, making your app feel professional and responsive.

Real Life Example

Think of an online store homepage that shows featured products immediately when you open it, without waiting for data to load after the page appears.

Key Takeaways

Manual data fetching on page load is repetitive and causes delays.

+page.js load functions fetch data before rendering, improving speed and code clarity.

This leads to better user experience and easier maintenance.

Practice

(1/5)
1. What is the main purpose of a load function in a +page.js file in SvelteKit?
easy
A. To fetch data or prepare information before the page is shown
B. To style the page with CSS
C. To handle user clicks on buttons
D. To define routes for the application

Solution

  1. Step 1: Understand the role of load in SvelteKit

    The load function runs before the page renders to get data or do setup.
  2. Step 2: Match the purpose with options

    Only To fetch data or prepare information before the page is shown describes fetching or preparing data before showing the page.
  3. Final Answer:

    To fetch data or prepare information before the page is shown -> Option A
  4. Quick Check:

    Page load functions fetch data before rendering [OK]
Hint: Load functions run before page shows to get data [OK]
Common Mistakes:
  • Confusing load with styling or event handling
  • Thinking load defines routes
  • Assuming load runs after page renders
2. Which of the following is the correct way to export a load function in +page.js?
easy
A. export default function load() { return { props: { message: 'Hi' } }; }
B. function load() { return { message: 'Hi' }; }
C. export function load() { return { props: { message: 'Hi' } }; }
D. export const load = () => { return { message: 'Hi' }; };

Solution

  1. Step 1: Recall correct export syntax for load

    In SvelteKit, load is exported as a named export, usually a const arrow function returning data without wrapping in props.
  2. Step 2: Check each option

    export const load = () => { return { message: 'Hi' }; }; exports load as a named const returning an object with data directly, which is correct. export function load() { return { props: { message: 'Hi' } }; } wrongly uses props key, function load() { return { message: 'Hi' }; } lacks export, export default function load() { return { props: { message: 'Hi' } }; } uses default export which is incorrect.
  3. Final Answer:

    export const load = () => { return { message: 'Hi' }; }; -> Option D
  4. Quick Check:

    Named export const load returns data object [OK]
Hint: Use named export const load returning data object [OK]
Common Mistakes:
  • Using default export instead of named export
  • Returning data inside a props object
  • Not exporting the load function
3. Given this +page.js code, what will be the value of data.greeting inside the page component?
export const load = () => {
  return { greeting: 'Hello, Svelte!' };
};
medium
A. undefined
B. 'Hello, Svelte!'
C. { greeting: 'Hello, Svelte!' }
D. An error occurs

Solution

  1. Step 1: Understand what load returns

    The load function returns an object with a key greeting and value 'Hello, Svelte!'.
  2. Step 2: How data is passed to the page

    The returned object keys become properties on the data object in the page component. So data.greeting equals 'Hello, Svelte!'.
  3. Final Answer:

    'Hello, Svelte!' -> Option B
  4. Quick Check:

    Returned keys become data props [OK]
Hint: Returned object keys become data properties [OK]
Common Mistakes:
  • Expecting the whole object as data.greeting
  • Thinking load returns props key
  • Assuming undefined if not wrapped in props
4. Identify the error in this +page.js load function:
export const load = async () => {
  const res = await fetch('/api/data');
  const data = await res.json();
  return data;
};
medium
A. The returned data must be wrapped in an object
B. fetch cannot be used inside load
C. The function should not be async
D. Missing export keyword

Solution

  1. Step 1: Check the return value of load

    The load function must return an object whose keys become props for the page. Returning raw data (like an array or primitive) is invalid.
  2. Step 2: Identify the fix

    Wrap the fetched data inside an object, e.g., return { data }, so the page receives it properly.
  3. Final Answer:

    The returned data must be wrapped in an object -> Option A
  4. Quick Check:

    Load returns object with keys for props [OK]
Hint: Always return an object from load function [OK]
Common Mistakes:
  • Returning raw data instead of object
  • Forgetting to export load
  • Thinking fetch is disallowed in load
5. You want to redirect users to the login page if they are not authenticated inside a +page.js load function. Which code snippet correctly does this?
hard
A. import { redirect } from '@sveltejs/kit'; export const load = () => { const user = null; if (!user) return redirect(302, '/login'); return { user }; };
B. export const load = () => { const user = null; if (!user) return '/login'; return { user }; };
C. import { redirect } from '@sveltejs/kit'; export const load = () => { const user = null; if (!user) throw redirect(302, '/login'); return { user }; };
D. export const load = () => { const user = null; if (!user) window.location.href = '/login'; return { user }; };

Solution

  1. Step 1: Understand how to redirect in load

    SvelteKit uses the redirect function from '@sveltejs/kit' which throws an exception to redirect the user.
  2. Step 2: Check each option

    import { redirect } from '@sveltejs/kit'; export const load = () => { const user = null; if (!user) throw redirect(302, '/login'); return { user }; }; correctly imports redirect and throws it when user is not authenticated. export const load = () => { const user = null; if (!user) return '/login'; return { user }; }; returns a string which is invalid. export const load = () => { const user = null; if (!user) window.location.href = '/login'; return { user }; }; uses browser redirect which won't work server-side. import { redirect } from '@sveltejs/kit'; export const load = () => { const user = null; if (!user) return redirect(302, '/login'); return { user }; }; returns redirect instead of throwing it, which is incorrect.
  3. Final Answer:

    import { redirect } from '@sveltejs/kit'; export const load = () => { const user = null; if (!user) throw redirect(302, '/login'); return { user }; }; -> Option C
  4. Quick Check:

    Throw redirect to redirect in load [OK]
Hint: Throw redirect() from load to redirect users [OK]
Common Mistakes:
  • Returning redirect instead of throwing it
  • Using window.location in load (server-side)
  • Returning a string URL to redirect
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard