It seems the user wants to implement a SvelteKit project focused on streaming SSR and partial hydration. They likely need clear instructions and example code for SvelteKit configuration, endpoints, and load functions with streaming SSR. I should keep it concise but include relevant code snippets. I also remember that since SvelteKit 2.0, there's a defer helper in load functions for streaming. I need to verify this with the knowledge I have up to October 2024.Clarifying SvelteKit Streaming SSR
I'm recalling that in Svelte 4 and SvelteKit 1, streaming SSR was mainly achieved through endpoints using text/event-stream. However, according to the SvelteKit 2 documentation, the defer import is from $app/forms.
I've got a code example in mind:
ts
import { dev } from '$app/environment';
import { error, redirect } from '@sveltejs/kit';
import { defer } from '$app/forms';
export const load = async () => {
return {
stream: defer(async () => {
// long task...
})
}
}
I need to confirm the origin of defer and ensure accuracy since streaming SSR should allow early HTML delivery while filling in placeholders once the promises resolve.Recapping SvelteKit Streaming and Await Blocks
In SvelteKit, I can utilize await within markup. Since Svelte 3, I've had access to {#await promise} blocks with then and catch, covering both client-side rendering and SSR. For server-side streaming, I can send a pending block initially, then once the promise resolves, send the remaining content. Actual streaming HTML support came to SvelteKit around 2023. I believe the await block is quite popular, and the new defer helper works seamlessly with it. Let's look for an example in the documentation.Examining the SvelteKit Defer Import
I have an example I want to analyze:
ts
import { defer } from '$app/server';
export async function load() {
return {
user: await getUser(),
stuff: defer(getStuff())
};
}
But I might be mixing up the import paths. defer could be from either $app/forms or $app/server. After considering it, $app/forms relates to form actions, not streaming. So, it seems more likely that defer is indeed from $app/server, while utilities like error and redirect come from @sveltejs/kit.Planning SvelteKit Implementation with Streaming SSR
The user likely wants to implement streaming SSR and partial hydration in a SvelteKit project. I think I’ll set csr=false globally to avoid hydration and create a ClientOnly component that loads dynamically with <ClientOnly>. The approach involves using defer to introduce interactive islands while keeping the top-level static.
I'll showcase a minimal project structure with essential files like +layout.svelte, +page.server.ts for streaming, and a ClientOnly component for lazy-loaded interactivity. It’s important to set the Node adapter to support streaming. Let’s outline the project steps and configuration!Implementing Streaming SSR with Partial Hydration
To implement streaming SSR, I'll start by creating the +page.server.ts file that sets up immediate data loading and fetches slow data asynchronously. The +page.svelte will then display this data, using an #await block for the slower promise.
Next, for partial hydration, I plan to develop a ClientOnly component that dynamically imports a Counter component. I realize it’s best to use a static version for SSR, then switch to the interactive one on the client side, ensuring a seamless experience. This approach balances initial rendering with client-side interactivity.Crafting Streaming SSR and Partial Hydration
I think I can create an effective approach to demonstrate partial hydration in SvelteKit. The idea is to render static markup for island components initially and then load the interactive elements client-side using onMount.
For ClientHydrate, I'll set it up to dynamically import and mount the Svelte component. To maintain a consistent experience, we need to ensure that the SSR output matches the static HTML in the client. I realize it’s simpler to create a clear structure for the demonstration, providing placeholder content while clearly explaining how the whole flow works. This way, I can present both streaming SSR and partial hydration effectively!Setting Up Streaming and Partial Hydration
I need to clarify the streaming configuration. Streaming is enabled by default, but we shouldn’t set config.kit.streaming = false. It's essential to note that streaming works only with specific adapters like Node, Vercel, or Cloudflare, and may not perform well behind caching proxies.
For partial hydration, I’ll incorporate import { browser } from '$app/environment'; for onMount and dynamic imports. I plan a clear, step-by-step guide for a new SvelteKit project, including file structure, project setup, adapter selection, and implementation of both streaming and partial hydration, wrapping up with a concise explanation. Below is a minimal but complete SvelteKit setup that demonstrates:
Streaming SSR using promises returned from load and {#await ...} blocks.
Partial hydration / islands using a small ClientOnly helper that lazy-loads interactive components on the client while the rest of the page is just normal SSR.
1. Create a SvelteKit project
bash
npm create svelte@latest streaming-ssr-partial-hydration
cd streaming-ssr-partial-hydration
npm install
We’ll make the root page stream: it sends initial HTML immediately and only later streams in slow data.
3.1 Server load with a slow promise
src/routes/+page.server.ts
ts
import type { PageServerLoad } from './$types';
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
async function getFastMessage() {
// imagine DB call or API
await sleep(200);
return 'This is fast server data.';
}
async function getSlowMessage() {
await sleep(3000);
return 'This is slow server data that arrived after ~3s.';
}
export const load: PageServerLoad = async () => {
const fast = await getFastMessage(); // blocks minimally
// IMPORTANT: do NOT await here => allows streaming
const slow = getSlowMessage();
return {
fast,
slow // a Promise<string>
};
};
3.2 Page using {#await} to drive streaming
src/routes/+page.svelte
svelte
<script lang="ts">
export let data: {
fast: string;
slow: Promise<string>;
};
</script>
<section>
<h2>Streaming SSR</h2>
<p>{data.fast}</p>
{#await data.slow}
<!-- This part is sent in the first chunk -->
<p>Loading slow data on the server...</p>
{:then slow}
<!-- This is streamed later as a second chunk -->
<p>{slow}</p>
{:catch err}
<p>Failed to load slow data: {String(err)}</p>
{/await}
</section>
How it behaves:
On first byte, you’ll already see:
<h2>Streaming SSR</h2>
the fast text
the “Loading slow data…” line
After ~3 seconds, the server streams a second HTML chunk that replaces the loading line with the final slow text.
To observe streaming clearly, run:
bash
npm run dev
# then, in another terminal
curl -N http://localhost:5173/
You should see HTML arriving in pieces.
4. Partial hydration / islands
Now add a “client-only” interactive component that’s not part of the initial SSR tree. The rest of the page is just normal SSR HTML.
4.1 Client-only helper (island wrapper)
This component:
Renders nothing on the server (or just a small placeholder).
On the client, uses onMount + dynamic import() to load an interactive Svelte component and mount it.
src/lib/ClientOnly.svelte
svelte
<script lang="ts">
import { onMount } from 'svelte';
import type { SvelteComponent } from 'svelte';
/**
* loader: () => import('./SomeComponent.svelte')
*/
export let loader: () => Promise<{ default: typeof SvelteComponent }>;
let Component: typeof SvelteComponent | null = null;
onMount(async () => {
const mod = await loader();
Component = mod.default;
});
</script>
<!-- Optional placeholder visible both SSR and before JS loads -->
<div data-client-only>
{#if Component}
<svelte:component this={Component} {...$$restProps} />
{:else}
<p>Loading interactive widget…</p>
{/if}
</div>
Key point: this component itself is part of the SvelteKit tree, but the actual interactive child is lazy-loaded only on the client.