Page data
A+page.svelte file can have a sibling +page.js that exports a load function:
src/routes/blog/[slug]/+page.js
src/routes/blog/[slug]/+page.svelte
The return value of a
load function is available to the page via the data prop.Layout data
Layoutload functions work the same way:
Define layout load
Create a
+layout.server.js file that returns datasrc/routes/blog/[slug]/+layout.server.js
page.data
Thepage store provides access to all data for the current page:
src/routes/+layout.svelte
Universal vs server load
There are two types ofload functions:
Universal load
- Files:
+page.js,+layout.js - Runs on both server and client
- Can return any value including classes
- Reruns in browser during hydration
Server load
- Files:
+page.server.js,+layout.server.js - Only runs on the server
- Must return serializable data
- Access to cookies, databases, secrets
When each runs
Server load functions
Server load functions
Always run on the server, both during SSR and when fetching data for client-side navigation.
Universal load functions
Universal load functions
- Run on the server during SSR
- Run again during hydration
- Run in the browser for subsequent navigations
- Can be disabled via
export const ssr = false
Combining both
When you have both, the serverload runs first and its output is passed to the universal load:
URL data
Load functions have access to URL information:Contains
origin, hostname, pathname, and searchParamsContains the route ID
Derived from
url.pathname and route.idMaking fetch requests
Use the providedfetch function in load:
Parent data
Access data from parentload functions with await parent():
When load reruns
SvelteKit tracks dependencies to avoid unnecessary reruns:Referenced params change
Referenced params change
If your
load uses params.slug, it reruns when slug changes.Referenced URL properties change
Referenced URL properties change
If your
load uses url.pathname or url.search, it reruns when those change.Search params accessed
Search params accessed
Calling
url.searchParams.get('x') makes it rerun when x changes.Parent reruns
Parent reruns
If a parent
load reruns and this load calls await parent().Manual invalidation
Manual invalidation
Via
invalidate(url), invalidateAll(), or depends().Streaming with promises
Return unresolved promises from serverload to stream data:
Streaming only works when JavaScript is enabled and on platforms that support streaming responses.
Learn more
Follow the interactive tutorial on loading data