The user wants a guide or code example on how to implement Server-Side Rendering (SSR) in a SvelteKit application, specifically focusing on:
- Dynamic Routes: Routes that depend on parameters (e.g.,
/product/123).
- Data Fetching: Getting data from an API or database on the server.
1. Understand SvelteKit's Rendering Modes:
- SvelteKit does SSR by default.
- The key file for data fetching and page configuration is the
+page.server.ts (or .js) file.
- The key file for the UI is the
+page.svelte file.
- Dynamic routes are defined by folder structure using square brackets, e.g.,
src/routes/blog/[slug]/+page.svelte.
2. Structure of the Solution:
I should provide a step-by-step tutorial or a complete example.
- Prerequisites: Basic SvelteKit setup.
- Step 1: Setting up the Dynamic Route: Explain the directory structure (
[param]).
- Step 2: Server-Side Data Loading (
+page.server.ts): This is where the core logic lies. I need to show the load function.
- Step 3: The Svelte Component (
+page.svelte): How to access the data passed from the server.
- Step 4: Error Handling: What happens if the data isn't found? (404s).
- Step 5: SEO (optional but relevant to SSR): Mentioning meta tags since the user asked about SSR.
3. Drafting the Content:
-
Scenario: Let's build a simple "Blog Post" or "Product Detail" page. A blog post using a [slug] is the standard example.
-
Directory Structure:
src/routes/blog/[slug]/+page.server.ts
src/routes/blog/[slug]/+page.svelte
-
The load function (Server-side):
- Import types (
Load or PageServerLoad).
- Access params (
params.slug).
- Fetch data (mocking an API call or using a dummy JSON placeholder).
- Return the data.
-
The View (+page.svelte):
- Use
$page.data or the data prop in the <script> tag (standard SvelteKit approach).
- Render the HTML.
-
Refining the "SSR" aspect:
- SvelteKit is SSR by default.
- I should explicitly mention that the code inside
+page.server.ts runs only on the server. This is crucial for hiding API keys or using database connections.
- If the user meant CSR (Client-Side Rendering) vs SSR, I should confirm that
+page.server.ts enforces server-side execution.
4. Writing the Code (Mental Draft):
-
+page.server.ts:
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
// fetch data based on params.slug
const res = await fetch(`https://api.example.com/posts/${params.slug}`);
const post = await res.json();
return { post };
};
-
+page.svelte:
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<h1>{data.post.title}</h1>
<p>{data.post.content}</p>
5. Adding Value:
- Error Handling: Use
error() from @sveltejs/kit.
- SEO: Briefly mention
<svelte:head>.
- Prerendering vs SSR: Just a quick note that this setup is dynamic (SSR), not static (SSG), unless
prerender: true is set.
6. Final Polish:
Make sure the syntax matches SvelteKit's latest conventions (SvelteKit 1.0+ or 2.0+). Stick to the +page.server.ts convention.
- Self-Correction during drafting: Should I use
+page.ts or +page.server.ts?
+page.ts: Runs on both server (during SSR) and client (during navigation).
+page.server.ts: Runs only on the server.
- Decision: Since the prompt asks specifically for "Server-Side Rendering" and usually implies securing data fetching or heavy server logic,
+page.server.ts is the correct, strict answer. It guarantees server execution.
7. Formatting the Output:
- Clear headings.
- Code blocks with file names.
- Explanations of why we are doing each step.
Let's construct the final response based on this structure. I will use a "Product Detail" scenario as it's practical.
- Route:
/product/[id]
- Mock Data: I'll create a helper function to simulate a database call so the code is runnable/demonstrable without an external API dependency, or just use
jsonplaceholder for realism. Let's stick to a generic fetch call for clarity.
Step-by-step Plan:
- Define the folder structure.
- Write the
load function in +page.server.ts.
- Write the UI in
+page.svelte.
- Handle 404 errors.
- Add SEO tags.
This looks solid. Proceeding to generate output.
Here is a comprehensive guide to implementing Server-Side Rendering (SSR) in SvelteKit with dynamic routes and data fetching.
In SvelteKit, SSR is the default behavior. The logic primarily lives in the load function inside a +page.server.ts file.
The Scenario
We will build a simple "Product Details" page.
- Dynamic Route:
/product/[id] (e.g., /product/1, /product/42).
- Data Fetching: The server will fetch product details from an external API (or database) before rendering the HTML.
Step 1: Create the Directory Structure
SvelteKit uses file-system based routing. To create a dynamic route, wrap the parameter name in square brackets.
Create the following folder structure inside src/routes/:
src/
└── routes/
└── product/
└── [id]/
├── +page.server.ts (Server-side logic)
└── +page.svelte (The UI)
Step 2: Implement Server-Side Logic (+page.server.ts)
This file runs only on the server. This is where you connect to databases or fetch private data.
File: src/routes/product/[id]/+page.server.ts
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
// Define the structure of our data (optional but good practice)
interface Product {
id: number;
title: string;
description: string;
price: number;
}
export const load: PageServerLoad = async ({ params, fetch }) => {
// 1. Access the dynamic parameter from the URL
const { id } = params;
// 2. Fetch data from an external API (Simulated with FakeStoreAPI)
// Note: Even though we use 'fetch' here, SvelteKit handles this specifically
// during SSR to eliminate latency and cache efficiently.
const response = await fetch(`https://fakestoreapi.com/products/${id}`);
// 3. Handle errors (e.g., 404 Not Found)
if (!response.ok) {
throw error(404, {
message: `Product with ID ${id} not found`
});
}
// 4. Parse the JSON
const product: Product = await response.json();
// 5. Return the data to the page
return {
product
};
};
Key Concepts:
params: Contains the dynamic route parameters (e.g., if the URL is /product/5, params.id is "5").
error: A helper from SvelteKit to throw HTTP errors properly.
- Return Object: Whatever you return here becomes available in the
.svelte file.
Step 3: Create the UI (+page.svelte)
SvelteKit automatically generates types for your data (if using TypeScript). The data passed from the server is available in the data prop.
File: src/routes/product/[id]/+page.svelte
<script lang="ts">
// Import the auto-generated type for type safety
import type { PageData } from './$types';
// The 'data' prop contains the result of the load function
export let data: PageData;
</script>
<div class="container">
<h1>{data.product.title}</h1>
<div class="product-details">
<img src={data.product.image} alt={data.product.title} />
<div class="info">
<p><strong>Price:</strong> ${data.product.price}</p>
<p><strong>Description:</strong> {data.product.description}</p>
<!-- SEO: The content below is rendered on the server -->
<p>This product was rendered server-side for ID: {data.product.id}</p>
</div>
</div>
</div>
<style>
.container { max-width: 800px; margin: 2rem auto; padding: 1rem; }
img { max-width: 200px; }
</style>
Step 4: SEO and Meta Tags (The "SSR" Advantage)
One of the main reasons for SSR is Search Engine Optimization. Because the data is loaded on the server, you can inject it into the <head> of your document.
Create a +page.svelte (or update the existing one) to include <svelte:head>:
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<!-- This updates the document <head> on the server -->
<svelte:head>
<title>{data.product.title} | My Store</title>
<meta name="description" content={data.product.description} />
</svelte:head>
<h1>{data.product.title}</h1>
<!-- ... rest of HTML ... -->
How it works under the hood
- Request: A user navigates to
/product/5.
- Server: The SvelteKit server recognizes the route matches
src/routes/product/[id].
- Execution: It executes the
load function in +page.server.ts.
- Fetch: The server fetches data from
fakestoreapi.com.
- Render: The server renders the HTML using
+page.svelte populated with the fetched data.
- Response: The browser receives fully formed HTML. The user sees the content immediately (good First Contentful Paint), and Google can read the meta tags.
Summary of Files
+page.server.ts: Backend logic. Runs on the server. Secure (can access DB secrets).
+page.svelte: Frontend UI. Receives data as a prop.
[id]: The folder name syntax creating the dynamic URL segment.