Day 3 of 5
⏱ ~60 minutes
Svelte in 5 Days — Day 3

SvelteKit Routing

SvelteKit turns your file system into routes. Every +page.svelte file becomes a page. This lesson covers file-based routing, layouts, nested routes, and loading data.

File-Based Routing

File Structure → Routes
src/routes/
├── +page.svelte           → /
├── about/
│   └── +page.svelte       → /about
├── blog/
│   ├── +page.svelte       → /blog
│   └── [slug]/
│       └── +page.svelte   → /blog/:slug
└── +layout.svelte         → wraps all pages
+layout.svelte







© 2026

Loading Data with load()

src/routes/blog/+page.js
// This runs on the server before the page renders
export async function load({ fetch }) {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=10');
  const posts = await res.json();
  return { posts };  // passed to +page.svelte as `data`
}
src/routes/blog/+page.svelte


Blog

{#each data.posts as post} {/each}
src/routes/blog/[slug]/+page.js
export async function load({ params, fetch }) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.slug}`);
  if (!res.ok) throw error(404, 'Post not found');
  const post = await res.json();
  return { post };
}
💡
The load function in +page.js runs on the server for SSR and on the client for client-side navigation. You get the best of both worlds — fast initial load and instant subsequent navigation.
📝 Day 3 Exercise
Build a Blog with Dynamic Routes
  1. Create a SvelteKit project. Build a layout with nav links to Home and Blog.
  2. Create /blog/+page.svelte with a load() function that fetches posts from JSONPlaceholder.
  3. Create /blog/[slug]/+page.svelte with a load function that fetches a single post by ID.
  4. Add error handling in the load function — throw a 404 if the post isn't found.
  5. Add a breadcrumb component that reads the current route from $page.url.pathname.

Day 3 Summary

  • +page.svelte files map to routes based on their directory location.
  • +layout.svelte wraps all child routes — perfect for nav, headers, footers.
  • +page.js exports a load() function that fetches data before the page renders.
  • Dynamic segments use [brackets] in folder names. Access them via params.slug.
Finished this lesson?