Lesson 2 of 9 beginner 5 min read

Routing

File-based routing with +page.svelte, +layout.svelte, +error.svelte, and dynamic segments [slug].

Interactive Laboratory

Live Runtime

Experiment directly with Routing concepts in real time

SvelteKit Full-Stack Pipeline
1. Request
Hook
2. Loader
load()
3. Server
SSR HTML
4. Browser
Hydrate

File-Based Routing in SvelteKit

In SvelteKit, your application’s routes are determined by the directory structure inside src/routes/.


1. Route File Conventions

FilePurpose
+page.svelteThe UI component for the route.
+page.ts / +page.server.tsData loading logic and server actions.
+layout.svelteWraps all child routes in a shared persistent layout.
+layout.ts / +layout.server.tsLoads shared data for layouts and all descendant pages.
+error.svelteCustom error fallback UI rendered when an error occurs.
+server.tsStandalone API endpoint (e.g. GET, POST, DELETE).

2. Dynamic Route Parameters ([slug])

To capture variable segments in a URL, wrap the folder name in brackets:

src/routes/guides/[slug]/+page.svelte

Inside your page component or load function, access the parameter:

// src/routes/guides/[slug]/+page.ts
import type { PageLoad } from './$types';
 
export const load: PageLoad = ({ params }) => {
	console.log('User navigated to guide slug:', params.slug);
	return {
		slug: params.slug
	};
};

3. Persistent Layouts (+layout.svelte)

Layouts wrap all nested pages. They don’t re-mount during navigation, preserving scroll positions, audio playback, and UI state:

<!-- src/routes/+layout.svelte -->
<script lang="ts">
	let { children } = $props();
</script>
 
<header>
	<nav><a href="/">Home</a> | <a href="/guides">Guides</a></nav>
</header>
 
<main>
	{@render children()}
</main>