Skip to content

Streaming a custom class promise from server to client fails when a load function is in +page.ts #14291

@OTheNonE

Description

@OTheNonE

Describe the bug

I have a custom class Point:

// lib/point.ts
export class Point {
	private _x: number
	private _y: number

	constructor(x: number, y: number) {
		this._x = x,
		this._y = y
	}

	get x() { return this._x }
	get y() { return this._y }
}

I have created the following transport definition for the class Point:

// hooks.ts
import type { Transport } from "@sveltejs/kit";
import { Point } from "$lib/point.ts";

export const transport: Transport = {
    Point: {
	    encode: (value) => value instanceof Point && { x: value.x, y: value.y },
	    decode: ({ x, y }) => new Point(x, y)
    }
};

I am streaming the custom class from the server:

// routes/+page.server.ts
import { Point } from "$lib/point.ts"
import { sleep } from "$lib/sleep.ts"

const createPoint = async (x: number, y: number) => {
	await sleep(1000)
	return new Point(x, y)
}

export const load = async () => {
	const point_promise = createPoint(5,6);
	return { point_promise };
};
<script>
        // +page.svelte
	let { data } = $props();
</script>

<h1>
	Coordinates:
	{#await data.point_promise}
		...loading...
	{:then point} 
		x: {point.x}
		y: {point.y}
	{/await}
</h1>

All this works! But if i add a load function inside of +page.ts and just pass the data along:

export async function load({ data }) {
	return { ...data }
}

The function fails due to the following error:

Error: Data returned from `load` while rendering / is not serializable: Cannot stringify arbitrary non-POJOs (point_promise). If you need to serialize/deserialze custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#Universal-hooks-transport
        at get.data (node_modules/@sveltejs/kit/src/runtime/server/page/load_data.js:211:23)
        at load (src/routes/+page.ts:4:23)

Reproduction

https://www.sveltelab.dev/93mw77a659044tg

Logs

System Info

System:
    OS: Windows 11 10.0.26100
    CPU: (12) x64 Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
    Memory: 3.62 GB / 15.79 GB
  Binaries:
    Node: 22.16.0 - C:\Program Files\nodejs\node.EXE
    npm: 11.4.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (139.0.3405.102)
  npmPackages:
    @sveltejs/adapter-auto: ^3.0.0 => 3.3.1
    @sveltejs/adapter-node: ^5.2.10 => 5.3.1
    @sveltejs/kit: ^2.0.0 => 2.36.1
    @sveltejs/vite-plugin-svelte: ^4.0.0-next.6 => 4.0.4
    svelte: ^5.38.1 => 5.38.1
    vite: ^5.0.3 => 5.4.19

Severity

blocking an upgrade

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions