CHAPTER 13
Beginner
Routing in Svelte
Updated: May 18, 2026
5 min read
# CHAPTER 13
Routing in Svelte
1. Chapter Introduction
A Single Page Application needs to display different views based on the URL without reloading the page. For plain Svelte (without SvelteKit), the popularsvelte-spa-router library provides a clean, declarative routing solution. For full-stack apps, SvelteKit's file-based routing is covered in the next chapter.
2. Learning Objectives
-
Install and configure
svelte-spa-router.
- Define routes and link between pages.
- Read route parameters.
- Implement a 404 page and redirect logic.
- Build a multi-page Svelte app.
3. Installing svelte-spa-router
bash
4. Setting Up Routes
javascript
svelte
5. Navigation with <Link> and push()
svelte
svelte
6. Route Parameters
svelte
7. Mini Project: Multi-Page App Structure
text
svelte
8. Active Link Styling
svelte
9. Common Mistakes
-
Forgetting hash-based URLs:
svelte-spa-routeruses hash-based routing by default (/#/products). For clean URLs (/products), use SvelteKit instead.
-
Not handling the 404 route: Always add a
'*': NotFoundcatch-all route.
10. MCQs
Question 1
What library enables client-side routing in plain Svelte?
Question 2
What is a dynamic route parameter?
Question 3
Where does svelte-spa-router inject the matching component?
Question 4
What function navigates to a route programmatically?
Question 5
What route pattern matches all unmatched routes?
Question 6
How do route parameters arrive in a route component?
Question 7
What store exposes the current URL path?
Question 8
What type of URLs does svelte-spa-router use by default?
Question 9
What SvelteKit feature replaces client-side routers for Svelte?
Question 10
How do you navigate back one step?
11. Interview Questions
- Q: What is the difference between hash-based and history-based routing?
- Q: When would you choose plain Svelte with svelte-spa-router versus SvelteKit?
12. Summary
svelte-spa-router provides a lightweight, declarative routing solution for Svelte SPAs. For production applications requiring SSR, file-based routing, and server endpoints, SvelteKit (covered next) is the preferred solution.