Server Load Functions with +page.server.js in SvelteKit
📖 Scenario: You are building a simple SvelteKit page that shows a list of books fetched from the server. The server will provide the data using a load function in +page.server.js. This simulates getting data from a database or API before the page renders.
🎯 Goal: Create a +page.server.js file with a load function that returns a list of books. Then use that data in the Svelte page to display the book titles.
📋 What You'll Learn
Create a books array with exact book objects in +page.server.js
Add a load function named load that returns the books array
Use the load function data in the Svelte page to display each book title
Ensure the Svelte page uses the export let data syntax to receive server data
💡 Why This Matters
🌍 Real World
Server load functions in SvelteKit are used to fetch data on the server before the page renders. This improves performance and SEO by sending fully prepared pages to the browser.
💼 Career
Understanding server load functions is essential for building modern web apps with SvelteKit. It helps developers create fast, data-driven pages and handle server-side logic cleanly.
Progress0 / 4 steps
1
Create the books data array in +page.server.js
In +page.server.js, create a constant array called books with these exact objects: { id: 1, title: 'Svelte for Beginners' }, { id: 2, title: 'Advanced SvelteKit' }, and { id: 3, title: 'JavaScript Essentials' }.
Svelte
Hint
Use export const books = [...] to create the array with the exact book objects.
2
Add the load function to return the books array
In +page.server.js, add an exported async function called load that returns an object with the key books set to the books array.
Svelte
Hint
Write export async function load() { return { books } } to send the books data to the page.
3
Receive the server data in the Svelte page
In the Svelte page file (e.g., +page.svelte), write export let data; at the top to receive the server data. Then create a {#each} block to loop over data.books and display each book's title inside a <li> element.
Svelte
Hint
Use export let data; to get the data, then {#each data.books as book} to loop and show titles.
4
Complete the Svelte page with semantic HTML and accessibility
Wrap the list of books inside a <section> with an aria-label of Book list. Add a heading <h2> with the text Available Books above the list.
Svelte
Hint
Use a <section aria-label="Book list"> and a heading <h2>Available Books</h2> above the list.
Practice
(1/5)
1. What is the main purpose of a server load function in a +page.server.js file in SvelteKit?
easy
A. To fetch or prepare data on the server before the page loads
B. To handle client-side user interactions
C. To style the page components
D. To manage browser cookies on the client
Solution
Step 1: Understand server load function role
Server load functions run on the server to get data before the page renders.
Step 2: Compare options to this role
Only To fetch or prepare data on the server before the page loads describes fetching or preparing data on the server side before page load.
Final Answer:
To fetch or prepare data on the server before the page loads -> Option A
Quick Check:
Server load function = fetch data before page load [OK]
Hint: Server load functions run on server, not client [OK]
Common Mistakes:
Confusing server load with client-side event handlers
Thinking server load manages styles or cookies
Assuming server load runs in the browser
2. Which of the following is the correct way to export a server load function in +page.server.js?
easy
A. export function load() { return { data: 'hello' }; }
C. export default function load() { return { data: 'hello' }; }
D. function load() { return { data: 'hello' }; }
Solution
Step 1: Recall SvelteKit server load export syntax
Server load functions are exported as named exports, usually as a const arrow function.
Step 2: Check each option
export const load = () => { return { data: 'hello' }; } uses export const load = () => { ... }, which is correct. export function load() { return { data: 'hello' }; } exports a function declaration but not as const, which is allowed but less common. export default function load() { return { data: 'hello' }; } uses default export which is incorrect. function load() { return { data: 'hello' }; } does not export at all.
B. Returning data directly instead of an object causes error
C. Fetching from '/api/data' on server causes an infinite loop
D. Missing export keyword
Solution
Step 1: Analyze fetch call in server load
The load function fetches from '/api/data', which is likely a route handled by the same app.
Step 2: Understand server fetch behavior
Fetching from an internal API route in server load can cause the server to call itself repeatedly, causing an infinite loop.
Final Answer:
Fetching from '/api/data' on server causes an infinite loop -> Option C
Quick Check:
Internal fetch in server load risks infinite loop [OK]
Hint: Avoid fetching internal routes directly in server load [OK]
Common Mistakes:
Thinking async is not allowed in load
Returning data directly is valid
Forgetting to export load function
5. You want to load user data securely on the server and pass it to the page. Which approach correctly uses +page.server.js to fetch user info from a database and expose only the username?
hard
A. export const load = async () => {
const user = await db.getUser();
return { username: user.username };
};
B. export const load = async () => {
const user = await db.getUser();
return user;
};
D. export const load = async () => {
const user = await fetch('/api/user');
return { user };
};
Solution
Step 1: Identify secure data fetching on server
export const load = async () => {
const user = await db.getUser();
return { username: user.username };
}; fetches user data directly from the database on the server, which is secure.
Step 2: Check data exposure
export const load = async () => {
const user = await db.getUser();
return { username: user.username };
}; returns only the username property, exposing minimal info to the page.
Step 3: Evaluate other options
export const load = async () => {
const user = await db.getUser();
return user;
}; returns full user object, exposing sensitive data. export const load = () => {
fetch('/api/user').then(res => res.json());
return {};
}; uses client fetch incorrectly in server load. export const load = async () => {
const user = await fetch('/api/user');
return { user };
}; fetches from API route which may cause loops or expose more data.