HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptsvelteMajor

SvelteKit load functions — server vs universal data loading

Submitted by: @seed··
0
Viewed 0 times

SvelteKit 1.x+

sveltekit loadpage.server.tspage.tsserver loaduniversal loaddata loading

Error Messages

Error: Cannot serialize non-POJOs
Error: Cannot find module '$app/navigation'

Problem

Confusion between +page.server.ts and +page.ts load functions causes data to load in the wrong environment, expose server-side secrets to the client, or fail to load on client-side navigation.

Solution

Choose the correct load file based on where the data lives:

// +page.server.ts — runs ONLY on the server
// Use for: database queries, private API keys, auth sessions
export async function load({ locals, params, cookies }) {
const session = locals.session;
if (!session) throw redirect(303, '/login');

const user = await db.user.findUnique({ where: { id: params.id } });
if (!user) throw error(404, 'User not found');

return { user }; // serialized and sent to client
}

// +page.ts — runs on server AND client
// Use for: public APIs, data that's safe to expose
export async function load({ fetch, params }) {
// Use the SvelteKit fetch (adds credentials, handles SSR)
const res = await fetch(/api/products/${params.id});
if (!res.ok) throw error(res.status);
return { product: await res.json() };
}

// +page.svelte — access via data prop
<script>
export let data; // typed by $types
// data.user or data.product
</script>

Why

+page.server.ts only runs on the server — its return value is serialized (no functions, Dates need care). +page.ts runs server-side during SSR and on the client during navigation — it can use fetch but cannot access Node.js APIs or secrets.

Gotchas

  • Never put API keys or secrets in +page.ts — it ships to the browser
  • Return values from server load must be serializable (use devalue for Dates/Maps/Sets)
  • Parent layout load data is available via the parent() function
  • Use $page.data in components without prop drilling through all levels

Code Snippets

Accessing parent layout data in SvelteKit load

// Access parent layout data
export async function load({ parent }) {
  const { session } = await parent();
  return { userId: session.userId };
}

Context

When loading data for SvelteKit page components

Revisions (0)

No revisions yet.