SvelteKit 05 🧡 Universal vs. Server load Functions — Fetching data in +page.ts vs. +page.server.ts and reading data via $props()
SvelteKit provides two distinct mechanisms for loading data into a route: Universal load functions and Server load functions. The choice between them dictates where the execution takes place, what data can be accessed, and how the application performs during client-side navigation. Understanding this distinction is critical for architecting a performant and secure application, as it separates the concerns of server-side data preparation from client-side data enhancement.
In Svelte 5, the result of these load functions is passed into the component as a data prop. By using the $props() rune, you can access this data reactively and cleanly. This chapter explores when to use each loader, how to secure private API keys, and how to leverage the hybrid nature of Universal loaders to create a seamless user experience that balances speed and security.
Key point: Use +page.server.ts to access private databases or sensitive API keys that must stay on the server, and use +page.ts for non-sensitive data that can be fetched in parallel or on the client during navigation; in both cases, the resulting data is accessed in the UI via the data prop using $props().
Why exists
The security boundary problem. Client-side code is visible to the user. Fetching data from a private database or using secret API keys inside a browser-side load function would expose these credentials, necessitating a server-only loader.
The latency optimization problem. Fetching data on the server eliminates the round-trip between the browser and the API. For data that is large or requires complex processing, executing on the server is almost always faster.
The client-side navigation fluidity. Universal load functions (+page.ts) run on the client during subsequent navigations. This reduces server load and allows the application to respond instantly when moving between routes.
The partial hydration requirement. Sometimes you need data that is only available in the browser (e.g., localStorage or browser-native APIs). Universal loaders are the only place where such browser-exclusive logic can reside alongside server-side logic.
The SEO and Initial Load performance. Server loaders ensure that HTML is generated with the necessary data already populated, providing search engines with full content and users with a “no-flash” initial experience.
a. Server-Side Data Loading (+page.server.ts)
The +page.server.ts loader executes exclusively on the server. This is the secure place for all database calls, internal service requests, and operations involving sensitive keys. When a user navigates to a route with a server loader, the browser sends an HTTP request, the server executes the code, and the results are serialized and sent to the client.
// src/routes/profile/+page.server.ts
export async function load({ locals }) {
// Can access private cookies or database
const user = await db.users.findUnique({ where: { id: locals.userId } });
return { user };
}
Because this runs only on the server, you can safely import modules that would otherwise crash in the browser (like fs or database drivers). This is the standard for 90% of data-fetching scenarios, particularly where user authentication or data privacy is involved.
b. Universal Data Loading (+page.ts)
The +page.ts loader is “universal.” It runs on the server during the initial page request (SSR) and on the client during subsequent navigations. This makes it ideal for fetching data from public APIs or for data that doesn’t require server-side secrets.
// src/routes/posts/+page.ts
export async function load({ fetch }) {
// Can be executed on the client during navigation!
const res = await fetch('https://api.public.com/posts');
return { posts: await res.json() };
}
The primary advantage of the Universal loader is the “handoff.” During the first visit, the server generates the data and includes it in the HTML. On the second visit, SvelteKit realizes it can run the load function in the browser, saving a round-trip to your server and drastically reducing the feel of “pageload” latency.
c. Consuming Data with $props()
Once a loader returns an object, SvelteKit passes it to the +page.svelte component as a data prop. In Svelte 5, you consume this by destructuring the data prop from the $props() rune.
<!-- src/routes/profile/+page.svelte -->
<script>
let { data } = $props();
</script>
<h1>Welcome, {data.user.name}</h1>
This access pattern is identical regardless of whether the data came from a server loader or a universal loader. SvelteKit ensures that the data prop is fully type-safe if you provide a return type for your load function. If you are using TypeScript, you can export a PageData type from your loader to ensure that your component knows exactly what shape the data prop has.
Complete Example Session
// ============================================
// PART 1: SERVER LOADER (PRIVATE)
// ============================================
// src/routes/admin/+page.server.ts
export async function load() {
return { secret: "Sensitive Information" };
}
// ============================================
// PART 2: UNIVERSAL LOADER (PUBLIC)
// ============================================
// src/routes/blog/+page.ts
export async function load() {
return { title: "My Blog" };
}
// ============================================
// PART 3: CONSUMING IN COMPONENT
// ============================================
// src/routes/admin/+page.svelte
<script>
let { data } = $props();
</script>
<p>{data.secret}</p>
// ============================================
// PART 4: TYPE SAFETY
// ============================================
// In +page.server.ts:
export type PageData = Awaited<ReturnType<typeof load>>;
This session showcases how different loaders are chosen based on data sensitivity and how the resulting data is unified by the component’s data prop.
Quick Reference
Loader Comparison
| Feature | +page.server.ts | +page.ts |
|---|---|---|
| Runs on Server | Always | Initial load |
| Runs on Client | Never | After navigation |
| Access secrets | Yes | No |
| Best for | DB/API Keys | Public/External APIs |
Data Access
let { data } = $props();
// Use data.property...
Best Practices
✅ Do This:
// Always type your load functions
export const load: PageLoad = async () => { ... }; // ✅
// Use server loaders for private data
// (Keeps keys out of the browser) // ✅
// Use universal loaders for fast nav
// (Speeds up app performance) // ✅
// Destructure data explicitly
let { data } = $props(); // ✅
❌ Don’t Do This:
// Put API keys in +page.ts
// (The user can see them in source code) // ❌
// Use server loaders if client-side is fine
// (Increases server load) // ❌
// Forget to handle errors in load
// (Use throw error() from @sveltejs/kit) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Leaked Key | Using +page.ts for secrets | Move logic to +page.server.ts |
| Slow UI | Universal loader blocking UI | Use await sparingly |
| Typing Mismatch | Implicit types | Define PageData type |
| Missing Data | Not returning an object | Ensure return { ... } |
Real-World Examples
1. Database user lookup
+page.server.ts fetching via Prisma/Drizzle.
2. Public API fetch
+page.ts fetching from a public JSON endpoint.
3. Shared layout loader
+layout.server.ts for global session data.
4. Type definition
export type PageData = ...
5. Error handling
import { error } from '@sveltejs/kit';
6. Redirecting
import { redirect } from '@sveltejs/kit';
7. Parallel fetch
await Promise.all([loadA(), loadB()])
8. Local browser logic
+page.ts accessing localStorage.
9. Dynamic route params
load({ params })
10. Data transformation
return { mappedData: ... }
Visual
Loader Execution Contexts
┌──────────────────────────────────────────────┐
│ +page.server.ts ──► Server Only │
│ │
│ +page.ts ──► Server (Initial) │
│ ──► Client (Nav) │
└──────────────────────────────────────────────┘
Data Flow to Component
┌──────────────────────────────────────────────┐
│ Loader ──► SvelteKit ──► data prop ──► $props()
└──────────────────────────────────────────────┘
Selection Matrix
┌──────────────────────────────────────────────┐
│ PRIVATE? ──► YES ──► +page.server.ts │
│ │ │
│ NO ──────► +page.ts (Universal) │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Universal loader | +page.ts |
| Server loader | +page.server.ts |
| Consuming data | let { data } = $props() |
| Type safety | PageData |
| Execution | Hybrid (Universal) vs Server |
Key takeaways:
- Security First. If you are touching a database or a secret API key, it must go in a
+page.server.tsloader. No exceptions. - Speed Second. Use
+page.tsfor your public API calls to allow SvelteKit to run the fetch on the client during navigation, saving your server from extra work. - Unify with Props. Don’t worry about where the data came from inside your component;
let { data } = $props()is the universal interface. - Type it. Always define the return type of your loaders to ensure your
dataprop is correctly typed throughout your component. - Use the Handoff. Universal loaders are powerful because they allow the server to do the work once, then let the browser take over, which is the “Goldilocks” zone of SvelteKit performance.
Remember: The division between Server and Universal loaders is your primary tool for managing the lifecycle of your data. By choosing the server for sensitive work and universal loaders for public data, you craft an app that is secure, fast, and highly responsive to user interaction.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!