Skip to content
TheChatArchiveThe Chat Archive
ClaudeClaude Haiku 4.5· anthropicHugging Face Frontier Reasoning Traces

I need to implement SSR in SvelteKit with streamed hydration - send the HTML shell…

  1. User

    I need to implement SSR in SvelteKit with streamed hydration - send the HTML shell immediately, then stream in the heavy chart data as it resolves. Show me how to handle database timeouts gracefully in the stream without breaking the HTML.

  2. Claude Assistant

    This is a great question about advanced SvelteKit features. The user wants to:

    1. Implement Server-Side Rendering (SSR) with streaming
    2. Send HTML shell immediately
    3. Stream in heavy chart data as it resolves
    4. Handle database timeouts gracefully without breaking HTML

    This involves:

    • SvelteKit's streaming capabilities
    • Svelte's {#await} blocks
    • Proper error handling in streams
    • Database timeout handling
    • Proper HTML structure integrity

    Let me create a comprehensive example showing:

    1. A +page.server.ts that returns streaming promises
    2. A +page.svelte that handles the streamed data with await blocks
    3. Error boundaries and timeout handling
    4. CSS for progressive loading states
    5. Proper database timeout configuration

    Key concepts:

    • SvelteKit supports returning promises from load functions
    • These promises are streamed to the client
    • The HTML shell is sent immediately
    • The client resolves the promises and updates the DOM
    • We need to handle timeouts gracefully with try-catch
    • We can use {#await} blocks with fallback UI

    SSR with Streamed Hydration in SvelteKit

    Here's a complete guide to implement streaming with graceful timeout handling:

    1. Server-Side Load with Streaming

    // src/routes/dashboard/+page.server.ts
    import { error } from '@sveltekit/adapter-auto';
    
    const DB_TIMEOUT = 5000; // 5 second timeout
    
    // Utility for timeout-wrapped promises
    function withTimeout<T>(
      promise: Promise<T>,
      timeoutMs: number,
      fallbackValue?: T
    ): Promise<T> {
      return Promise.race([
        promise,
        new Promise<T>((_, reject) =>
          setTimeout(
            () => reject(new Error(`Timeout after ${timeoutMs}ms`)),
            timeoutMs
          )
        ),
      ]).catch((err) => {
        if (fallbackValue !== undefined) {
          console.warn(`Query timeout, using fallback:`, err.message);
          return fallbackValue;
        }
        throw err;
      });
    }
    
    // Simulate heavy database queries
    async function fetchChartData() {
      const delay = Math.random() * 6000; // Simulates 0-6s delay
      await new Promise((r) => setTimeout(r, delay));
      
      if (Math.random() > 0.8) {
        throw new Error('Database connection failed');
      }
    
      return {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
        datasets: [
          {
            label: 'Revenue',
            data: Array.from({ length: 5 }, () => Math.random() * 1000),
          },
        ],
      };
    }
    
    async function fetchAnalytics() {
      await new Promise((r) => setTimeout(r, Math.random() * 4000));
      return {
        totalUsers: 15420,
        activeToday: 3210,
        conversionRate: 0.0342,
      };
    }
    
    async function fetchLeaderboard() {
      await new Promise((r) => setTimeout(r, Math.random() * 7000));
      return [
        { id: 1, name: 'Alice', score: 9800 },
        { id: 2, name: 'Bob', score: 8750 },
        { id: 3, name: 'Carol', score: 8420 },
      ];
    }
    
    export async function load({ depends }) {
      // Tell SvelteKit to invalidate when data changes
      depends('data:dashboard');
    
      return {
        // Immediate shell
        title: 'Dashboard',
        
        // Streamed data - these resolve after HTML is sent
        chartData: withTimeout(fetchChartData(), DB_TIMEOUT, {
          labels: [],
          datasets: [{ label: 'Revenue', data: [] }],
        }),
        
        analytics: withTimeout(fetchAnalytics(), DB_TIMEOUT, {
          totalUsers: 0,
          activeToday: 0,
          conversionRate: 0,
        }),
        
        leaderboard: withTimeout(fetchLeaderboard(), DB_TIMEOUT, []),
      };
    }
    

    2. Component with Error Boundaries

    <!-- src/routes/dashboard/+page.svelte -->
    <script>
      import { onMount } from 'svelte';
      import ChartWidget from './ChartWidget.svelte';
      import AnalyticsWidget from './AnalyticsWidget.svelte';
      import LeaderboardWidget from './LeaderboardWidget.svelte';
    
      export let data;
    
      let retryKey = {};
    
      function retryAll() {
        retryKey = {};
      }
    
      onMount(() => {
        // Optional: Re-validate data if needed
        const timer = setTimeout(() => {
          console.log('Checking data freshness...');
        }, 30000);
    
        return () => clearTimeout(timer);
      });
    </script>
    
    <div class="dashboard">
      <header>
        <h1>Dashboard</h1>
        <button on:click={retryAll} class="retry-btn">
          ↻ Retry Failed Data
        </button>
      </header>
    
      <main>
        <!-- Chart Widget -->
        <section class="card">
          <h2>Revenue Chart</h2>
          {#await data.chartData}
            <div class="skeleton loading">
              <div class="skeleton-bar" />
              <div class="skeleton-bar" />
              <div class="skeleton-bar" />
            </div>
          {:then chartData}
            <ChartWidget {chartData} />
          {:catch error}
            <div class="error-state">
              <p>Failed to load chart: {error.message}</p>
              <p class="hint">
                {#if error.message.includes('Timeout')}
                  Database took too long to respond. Showing fallback data.
                {:else}
                  Please try again later.
                {/if}
              </p>
              <button on:click={retryAll}>Retry</button>
            </div>
          {/await}
        </section>
    
        <!-- Analytics Widget -->
        <section class="card">
          <h2>Analytics</h2>
          {#await data.analytics}
            <div class="skeleton">
              <div class="stat-placeholder" />
              <div class="stat-placeholder" />
              <div class="stat-placeholder" />
            </div>
          {:then analytics}
            <AnalyticsWidget {analytics} />
          {:catch error}
            <div class="error-state">
              <p>⚠ Analytics unavailable</p>
              <button on:click={retryAll}>Reload</button>
            </div>
          {/await}
        </section>
    
        <!-- Leaderboard Widget -->
        <section class="card">
          <h2>Top Performers</h2>
          {#await data.leaderboard}
            <div class="skeleton">
              <div class="list-item-placeholder" />
              <div class="list-item-placeholder" />
              <div class="list-item-placeholder" />
            </div>
          {:then leaderboard}
            <LeaderboardWidget {leaderboard} />
          {:catch error}
            <div class="error-state">
              <p>Could not fetch leaderboard</p>
              <button on:click={retryAll}>Try Again</button>
            </div>
          {/await}
        </section>
      </main>
    </div>
    
    <style>
      .dashboard {
        padding: 2rem;
        max-width: 1200px;
        margin: 0 auto;
      }
    
      header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2rem;
      }
    
      main {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
      }
    
      .card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      }
    
      .card h2 {
        margin: 0 0 1rem 0;
        font-size: 1.125rem;
        color: #333;
      }
    
      /* Skeleton Loaders */
      .skeleton {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
      }
    
      .skeleton-bar {
        height: 200px;
        background: linear-gradient(
          90deg,
          #f0f0f0 25%,
          #e0e0e0 50%,
          #f0f0f0 75%
        );
        background-size: 200% 100%;
        animation: loading 1.5s infinite;
        border-radius: 4px;
      }
    
      .stat-placeholder {
        height: 60px;
        background: linear-gradient(
          90deg,
          #f0f0f0 25%,
          #e0e0e0 50%,
          #f0f0f0 75%
        );
        background-size: 200% 100%;
        animation: loading 1.5s infinite;
        border-radius: 4px;
      }
    
      .list-item-placeholder {
        height: 40px;
        background: linear-gradient(
          90deg,
          #f0f0f0 25%,
          #e0e0e0 50%,
          #f0f0f0 75%
        );
        background-size: 200% 100%;
        animation: loading 1.5s infinite;
        border-radius: 4px;
      }
    
      @keyframes loading {
        0% {
          background-position: 200% 0;
        }
        100% {
          background-position: -200% 0;
        }
      }
    
      /* Error States */
      .error-state {
        background: #fff3cd;
        border: 1px solid #ffc107;
        border-radius: 4px;
        padding: 1rem;
        text-align: center;
      }
    
      .error-state p {
        margin: 0.5rem 0;
        color: #856404;
      }
    
      .error-state .hint {
        font-size: 0.875rem;
        color: #9a7e12;
      }
    
      .error-state button {
        margin-top: 0.75rem;
        padding: 0.5rem 1rem;
        background: #ffc107;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-weight: 500;
      }
    
      .error-state button:hover {
        background: #ffb300;
      }
    
      .retry-btn {
        padding: 0.5rem 1rem;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-weight: 500;
      }
    
      .retry-btn:hover {
        background: #0056b3;
      }
    </style>
    

    3. Individual Widget Components

    <!-- src/routes/dashboard/ChartWidget.svelte -->
    <script>
      import { onMount } from 'svelte';
      
      export let chartData;
      let canvas;
    
      onMount(() => {
        // Simulate heavy chart library loading
        if (chartData.datasets[0].data.length === 0) {
          console.log('Using placeholder chart');
        }
      });
    </script>
    
    <div class="chart-container">
      <canvas bind:this={canvas} />
      {#if chartData.datasets[0].data.length === 0}
        <p class="note">Showing fallback data due to timeout</p>
      {/if}
    </div>
    
    <style>
      .chart-container {
        position: relative;
      }
    
      .note {
        font-size: 0.875rem;
        color: #999;
        margin-top: 0.5rem;
      }
    </style>
    
    <!-- src/routes/dashboard/AnalyticsWidget.svelte -->
    <script>
      export let analytics;
    </script>
    
    <div class="analytics">
      <div class="stat">
        <h3>Total Users</h3>
        <p class="value">{analytics.totalUsers.toLocaleString()}</p>
      </div>
      <div class="stat">
        <h3>Active Today</h3>
        <p class="value">{analytics.activeToday.toLocaleString()}</p>
      </div>
      <div class="stat">
        <h3>Conversion</h3>
        <p class="value">{(analytics.conversionRate * 100).toFixed(2)}%</p>
      </div>
    </div>
    
    <style>
      .analytics {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1rem;
      }
    
      .stat {
        text-align: center;
      }
    
      .stat h3 {
        margin: 0 0 0.5rem 0;
        font-size: 0.875rem;
        color: #999;
        text-transform: uppercase;
      }
    
      .value {
        margin: 0;
        font-size: 1.75rem;
        font-weight: bold;
        color: #333;
      }
    </style>
    
    <!-- src/routes/dashboard/LeaderboardWidget.svelte -->
    <script>
      export let leaderboard;
    </script>
    
    <table class="leaderboard">
      <tbody>
        {#each leaderboard as item (item.id)}
          <tr>
            <td class="rank">{leaderboard.indexOf(item) + 1}.</td>
            <td class="name">{item.name}</td>
            <td class="score">{item.score.toLocaleString()}</td>
          </tr>
        {/each}
      </tbody>
    </table>
    
    <style>
      .leaderboard {
        width: 100%;
        border-collapse: collapse;
      }
    
      tr {
        border-bottom: 1px solid #eee;
      }
    
      td {
        padding: 0.75rem 0;
      }
    
      .rank {
        font-weight: bold;
        color: #007bff;
        width: 2rem;
      }
    
      .name {
        flex: 1;
      }
    
      .score {
        text-align: right;
        font-weight: 500;
      }
    </style>
    

    4. Advanced: Custom Streaming with TextEncoder

    For more control, you can use streaming directly:

    // src/routes/advanced/+page.server.ts
    import type { PageServerLoad } from './$types';
    
    export const load: PageServerLoad = async ({ fetch }) => {
      // Return a stream-ready object
      const chartDataPromise = new Promise((resolve) => {
        setTimeout(
          () =>
            resolve({
              labels: ['A', 'B', 'C'],
              data: [10, 20, 30],
            }),
          2000
        );
      });
    
      return {
        streamed: {
          chart: chartDataPromise,
          // Other streams...
        },
      };
    };
    
    <!-- src/routes/advanced/+page.svelte -->
    <script>
      export let data;
    </script>
    
    {#if data.streamed}
      {#await data.streamed.chart}
        <p>Loading chart...</p>
      {:then chart}
        <p>Chart data: {JSON.stringify(chart)}</p>
      {:catch error}
        <p>Error: {error.message}</p>
      {/await}
    {/if}
    

    5. Testing Timeouts

    // src/lib/testUtils.ts
    export function simulateSlowQuery(
      delayMs: number,
      shouldFail = false
    ) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (shouldFail) {
            reject(new Error('Simulated database failure'));
          } else {
            resolve({ success: true });
          }
        }, delayMs);
      });
    }
    

    Key Benefits

    ✅ HTML shell sent immediately - User sees page structure instantly
    ✅ Progressive enhancement - Data loads as available
    ✅ Graceful degradation - Timeouts use fallback data
    ✅ No broken HTML - Error boundaries prevent layout shifts
    ✅ Retry capability - Users can manually refresh failed sections
    ✅ SEO friendly - Initial render includes structure

    This approach gives you the best of both worlds: fast initial page load with progressive data hydration!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.