In SvelteKit, the load function can run on the server before the page renders. Why is this behavior important?
Think about where sensitive data like API keys should be kept.
The load function runs on the server so it can fetch data securely without exposing sensitive information like API keys to the browser. This helps keep secrets safe and improves performance by sending ready data to the client.
Consider a SvelteKit page that fetches data inside the load function versus fetching data inside onMount in the component. What is a key difference in user experience?
Think about when the data is ready to show to the user.
When data is fetched in load, the page waits for the data before rendering, so users see content immediately. Fetching in onMount happens after the page loads, causing a delay before data appears.
Which of the following load functions correctly fetches JSON data from an API server-side in SvelteKit?
export async function load() { // fetch data here }
Remember that server-side fetch needs full URL or relative to server, and load must be async to await fetch.
Option D correctly uses async/await with a full URL to fetch data server-side and returns it properly. Option D uses a relative URL which may not work server-side. Option D is missing async/await and does not return properly. Option D incorrectly calls .json() without awaiting fetch.
Given this load function, why does it cause a runtime error?
export async function load() { const response = await fetch('/api/data'); const data = await response.json(); return data; }
Check what the load function expects to return.
The load function must return an object with properties to be passed as props to the page. Returning raw data directly causes a runtime error because SvelteKit expects an object.
Consider this SvelteKit page code:
+page.svelte
<script>
export let data;
</script>
<h1>User: {data.user.name}</h1>
+page.server.js
export async function load() {
return { user: { name: 'Alice' } };
}What will the page display when loaded?
Remember how data returned from load is passed as props.
The load function returns an object with user. This is passed as data prop to the page. The page displays User: Alice correctly.