Elementary, my dear developer. Server-side rendering (SSR) is SvelteKit's default behavior for dynamic routes when using a server adapter (e.g., adapter-node). Data fetching happens in +page.server.js via the load function, which runs on the server, injects props into your page, and enables SEO-friendly, fast initial loads.
I'll walk you through a complete, minimal implementation for a dynamic route like /posts/[slug] that fetches post data server-side. This uses an in-memory data store for simplicity (replace with your API/database).
1. Project Setup
bash Copy code
npm create svelte@latest my-ssr-app
cd my-ssr-app
npm install
npm install @sveltejs/adapter-node # For SSR on Node.js server
In svelte.config.js:
js Copy code
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
kit: {
adapter: adapter()
},
preprocess: vitePreprocess()
};
2. File Structure
code Copy code
src/
routes/
posts/
[slug]/
+page.server.js # Server-side load function
+page.svelte # Page component (SSR + CSR)
3. Data Fetching: src/routes/posts/[slug]/+page.server.js
This runs only on the server during SSR (and client-side navigation). It fetches data based on the dynamic slug param.
js Copy code
// Mock data store (replace with fetch('/api/posts/' + slug) or Prisma/Supabase/etc.)
const posts = {
'hello-world': {
title: 'Hello, World!',
content: 'This post was fetched server-side for SSR magic.',
date: new Date().toISOString()
},
'sveltekit-rules': {
title: 'SvelteKit Rules',
content: 'Dynamic routes + SSR = 🚀',
date: new Date().toISOString()
}
};
export async function load({ params }) {
const { slug } = params;
if (!posts[slug]) {
throw error(404, 'Post not found');
}
return {
post: posts[slug],
slug
};
}
4. Page Component: src/routes/posts/[slug]/+page.svelte
Uses the data from load(). SvelteKit serializes it safely for SSR.
svelte Copy code
<script>
export let data;
// data.post, data.slug available immediately on SSR
</script>
<svelte:head>
<title>{data.post.title}</title>
<meta name="description" content={data.post.content.slice(0, 160)} />
</svelte:head>
<article>
<h1>{data.post.title}</h1>
<time>{new Date(data.post.date).toLocaleDateString()}</time>
<p>{data.post.content}</p>
</article>
<style>
article { max-width: 800px; margin: 0 auto; padding: 2rem; }
</style>
5. Run It
bash Copy code
npm run dev # http://localhost:5173/posts/hello-world
# Build & preview: npm run build && npm run preview
How It Works
Dynamic Route : [slug] matches /posts/hello-world, injecting params.slug = 'hello-world'.
SSR Flow :
Browser requests /posts/hello-world.
SvelteKit runs load() on server , fetches data.
Renders full HTML with hydrated data (view source: data is inlined).
Ships JS bundle for client-side interactivity.
Client-Side Navigation : Navigating to /posts/sveltekit-rules calls load() on client (faster, no full reload).
Error Handling : 404s are automatic.
SEO/Performance : Pre-rendered HTML with meta tags.
Pro Tips
Real API : Replace mock with const res = await fetch(https://api.example.com/posts/${slug}` ); return { post: await res.json() };`.
Streaming : Add stream: true in svelte.config.js for progressive rendering.
Prerender Static Routes : Use export const prerender = true; in +page.js for static pages; dynamic stays SSR.
TypeScript : Add types to load({ params }: { params: { slug: string } }).
Auth/Env : Use event.locals or process.env in load().
View source on /posts/hello-world—you'll see the rendered content. Case closed. Questions?