Bird
Raised Fist0
Svelteframework~10 mins

Page load functions (+page.js) in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Page load functions (+page.js)
Page request
↓
+page.js load function runs
↓
Fetch or prepare data
↓
Return data object
↓
Page component receives data
↓
Page renders with data
When a page loads, the +page.js file's load function runs first to get data, then passes it to the page component to render.
Execution Sample
Svelte
export async function load({ fetch }) {
  const res = await fetch('/api/data');
  const data = await res.json();
  return { data };
}
This load function fetches data from an API and returns { data } which becomes the `data` prop for the page component.
Execution Table
StepActionEvaluationResult
1Page requested by userN/ATrigger +page.js load function
2Run load functionCall load({ fetch })Start async fetch
3Fetch data from /api/dataAwait fetchResponse received
4Parse JSON from responseAwait res.json()Data object created
5Return data objectreturn { data }Data ready for page
6Page component receives dataData passed inPage renders with data
💡 Load function completes and returns data object, page renders with data.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
resundefinedResponse objectResponse objectResponse object
dataundefinedundefinedParsed JSON objectParsed JSON object
Key Moments - 3 Insights
Why do we use 'await' inside the load function?
Because the fetch and res.json() are asynchronous, 'await' pauses execution until data is ready, as shown in steps 3 and 4 of the execution_table.
What happens if the load function does not return { data }?
The page component will not receive any data to render. Step 5 shows returning { data } is necessary for passing data to the page.
Is the load function run on the server or client?
+page.js load runs on the server for initial loads (SSR) and on the client for navigations to fetch data before rendering.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what variable holds the parsed JSON data after step 4?
Adata
Bres
Cprops
Dload
💡 Hint
Check the variable_tracker row for 'data' after step 4.
At which step does the page component receive the data to render?
AStep 3
BStep 5
CStep 6
DStep 4
💡 Hint
Look at the execution_table row describing when data is passed to the page.
If the fetch call fails, what will happen to the load function execution?
AIt will return empty props immediately
BIt will throw an error and stop before returning data
CIt will skip parsing JSON and return undefined
DIt will continue and return stale data
💡 Hint
Consider what happens if 'await fetch' fails at step 3 in the execution_table.
Concept Snapshot
Page load functions (+page.js):
- Export an async 'load' function
- Fetch or prepare data inside it
- Return object like { data }
- Object passed as `data` prop to page component
- Runs before page renders (server/client)
Full Transcript
When a user requests a page, SvelteKit runs the +page.js load function first. This function can fetch data asynchronously using 'await'. After fetching and parsing data, it returns { data }, which becomes the `data` prop. The page component receives `data` and renders the page with the data. If the fetch fails, the load function throws an error and stops. This process ensures the page has all needed data before showing to the user.

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