I've been mapping out the steps to create a SvelteKit project. Focusing on the goal, which is a project demoing Streaming SSR and Partial Hydration. I'm prioritizing the user's needs, starting with these performance features and thinking about how they enhance the user experience.
Considering SvelteKit Architecture
I'm now diving deeper into how SvelteKit handles hydration. I'm focusing on the default behavior and how it contrasts with a traditional "islands" architecture. The aim is to clarify how to get the benefits of partial hydration without necessarily using the islands pattern directly. I'm also considering the implications of client-side routing.
Clarifying Implementation Steps
I'm now detailing the steps. I've broken them down into phases: setup, backend data simulation (using promises to mimic slow calls), frontend component integration with {#await}, streaming configuration in the load function, and finally, optimization, focusing on strategies that give the same effect as partial hydration. I'm clarifying how to leverage SvelteKit's streaming and deferred rendering capabilities, using csr = false, to control which parts of the page hydrate and when.
Structuring the Implementation Guide
I'm now structuring the guide. I'm focusing on the implementation steps. I've defined the key areas, including setting up the project, simulating backend data delays, and using Svelte's {#await} blocks. I'm also ensuring the load function's nested promise structure works. Finally, I'm clarifying how to make components server-side render, for example, by not using csr = false.
Outlining the Guide Structure
I'm now consolidating the guide's structure. I'm prioritizing clarity. I'll include the steps for project setup, backend data simulation (to demonstrate streaming SSR), and frontend integration. Additionally, I'll explain how to get the most benefit out of streaming. I will also incorporate how to use the csr = false option to make a mostly SSR page, but will clarify the best way to get granular hydration in the context of SvelteKit.
Synthesizing Guide Components
I'm now integrating the guide components. I'm focusing on assembling the code examples, including the backend load function and the frontend page components, using the {#await} block. Also, I'm incorporating the export const csr = false strategy to achieve the desired effect of limited client-side hydration, and I'll explain how it improves performance.
Refining Guide Content
I'm now iterating on the guide's content. I'm focusing on the load function and the usage of the {#await} block. Also, I'm incorporating the explanation of csr = false and how it can be used to mimic partial hydration by preventing unnecessary client-side JS execution. I'll add a section with browser dev tool instructions, so the user can verify the streaming.
Here is a complete guide to implementing Streaming SSR in SvelteKit.
It is important to note a technical distinction: SvelteKit does not support "Partial Hydration" (Islands Architecture) in the same way frameworks like Astro or Fresh do out of the box. SvelteKit generally hydrates the entire page context.
However, you can achieve the performance benefits associated with partial hydration by combining Streaming SSR (sending HTML immediately) with Progressive Enhancement (rendering content before JavaScript loads).
Below is a step-by-step implementation.
Prerequisites
Node.js installed.
Terminal.
Step 1: Scaffolding the Project
Run the following commands to create a skeleton SvelteKit project.
bash
npm create svelte@latest sveltekit-streaming-demo
# Select: Skeleton project, TypeScript (or JS), Prettier/ESLint as desired
cd sveltekit-streaming-demo
npm install
Step 2: Understanding Streaming SSR
In SvelteKit, Streaming SSR allow you to send the HTTP headers and the initial HTML (Layout, Navbar, SEO tags) immediately to the browser, while keeping the connection open to stream in "slow" data (like database queries) via promises.
The Rule: To stream data, you must notawait the promise in the top level of your load function. You must return the promise nested inside the data object.
Step 3: Implement the Server Loader (+page.server.ts)
Create or edit src/routes/+page.server.ts. We will simulate a fast data source (CMS) and a slow data source (Analytics/DB).
typescript
// src/routes/+page.server.ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
// 1. Fetch critical data (we await this so it renders immediately)
const criticalData = await getCriticalContent();
// 2. Initiate slow data fetch (Do NOT await this!)
// This creates a pending Promise that SvelteKit will stream to the client.
const streamData = getSlowAnalyticsData();
return {
content: criticalData,
// 3. Pass the promise. SvelteKit detects this is a promise
// and defers it, keeping the HTTP connection open.
streamed: {
analytics: streamData
}
};
};
// Simulating a fast API call (e.g., 50ms)
async function getCriticalContent() {
return { title: 'Welcome to Streaming SSR', description: 'This loads instantly.' };
}
// Simulating a slow DB call (e.g., 3 seconds)
async function getSlowAnalyticsData() {
return new Promise<{ visitors: number; revenue: number }>((resolve) => {
setTimeout(() => {
resolve({ visitors: 12543, revenue: 5400 });
}, 3000);
});
}
Step 4: Implement the View (+page.svelte)
Now we use Svelte's {#await} block. This is where the magic happens. SvelteKit renders the loading state on the server, sends that HTML, and then swaps it out for the resolved data when the stream finishes (hydration).
svelte
<!-- src/routes/+page.svelte -->
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="container">
<!-- 1. This renders immediately because we awaited it in the server load function -->
<section class="hero">
<h1>{data.content.title}</h1>
<p>{data.content.description}</p>
</section>
<hr />
<!-- 2. This handles the Streaming Data -->
<section class="dashboard">
<h2>Live Analytics</h2>
<!--
We access the nested promise here.
SERVER SIDE: SvelteKit sends the HTML for the {:catch} or text immediately if it's pending.
CLIENT SIDE: Once the chunk arrives, Svelte hydrates this specific block.
-->
{#await data.streamed.analytics}
<!-- LOADING STATE -->
<div class="skeleton">
<p>Connecting to database...</p>
<div class="loader"></div>
</div>
{:then analytics}
<!-- RESOLVED STATE -->
<div class="stats-grid">
<div class="card">
<h3>Visitors</h3>
<p>{analytics.visitors}</p>
</div>
<div class="card">
<h3>Revenue</h3>
<p>${analytics.revenue}</p>
</div>
</div>
{:catch error}
<!-- ERROR STATE -->
<p class="error">Failed to load analytics.</p>
{/await}
</section>
</div>
<style>
.container { max-width: 800px; margin: 0 auto; font-family: sans-serif; padding: 2rem; }
.skeleton { background: #f4f4f5; padding: 2rem; border-radius: 8px; text-align: center; }
.stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.card { border: 1px solid #ddd; padding: 1rem; border-radius: 8px; }
.loader {
width: 20px; height: 20px; border: 3px solid #ccc; border-top-color: #333;
border-radius: 50%; animation: spin 1s linear infinite; margin: 10px auto;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
While SvelteKit hydrates the root, you can control hydration cost. If you have a route that is purely informational (like a blog post) and doesn't strictly need interactive JavaScript, you can disable hydration for that specific page.
Create a new route src/routes/static-demo/+page.svelte and src/routes/static-demo/+page.ts.
In src/routes/static-demo/+page.ts:
typescript
// This disables Client Side Rendering (Hydration) for this page entirely.
// HTML is sent, but Svelte won't attach JS listeners.
// This simulates "Islands" by having some pages carry 0KB of JS bundle payload.
export const csr = false;
However, standard SvelteKit streaming (Step 4) requires JS to process the stream into the DOM. If you want Streaming AND no-JS (Progressive Enhancement), SvelteKit handles this automatically:
If JS is enabled: The stream resolves, populates the DOM.
If JS is disabled in browser: SvelteKit will actually wait on the server for the full data before sending HTML (falling back to standard SSR), ensuring the user still sees content.
Step 6: Verification
Run the server:
bash
npm run dev
Open http://localhost:5173.
Observe:
The "Welcome" title appears instantly.
The "Connecting to database..." skeleton loader appears instantly.
3 seconds later, the skeleton is replaced by the numbers.
Check Network Tab:
Refresh the page.
Click on the request for localhost.
Look at the Timing tab. You will see "Time to First Byte" (TTFB) is low (fast), but "Content Download" takes 3 seconds. This confirms the HTML was streaming in chunks.
Summary of Architecture
SSR: The server starts rendering HTML immediately.
Streaming: The server encounters the Promise in the load function. Instead of waiting, it sends down the placeholder HTML produced by the {#await} block.
Hydration:
Once the HTML lands in the browser, Svelte boots up.
When the server promise resolves, SvelteKit sends a script chunk to the browser containing the data.
The Svelte client-side router picks up this data and updates the {#await} block to the {:then} state without a full page reload.