Search⌘ K
AI Features

Implementing Routing in Svelte

Explore how to implement routing in Svelte with the svelte-routing package to build multi-page applications. Learn to define static and dynamic routes, use the Router, Route, and Link components, and handle programmatic navigation. Understand how to manage navigation to valid pages and update links for client-side routing, creating a seamless single-page app experience.

So far, we've only worked on one page, but most web applications have multiple pages. In this lesson, we're going to take a look at how to implement routing in Svelte to create more pages and navigate between them.

By default, Svelte doesn't have a built-in way to handle routing, so we're going to use a third-party community-developed package called svelte-routing. We're going to define all routes at the root of our application, App.svelte:

<script>
  import { state } from '../state'
  import Header from '../components/Header.svelte'

  export let id;

  const student = $state.students.find(student => [id, Number(id)].includes(student.id));
</script>

<Header />
details view for: {id}
Add routes

We need to import the Router and Route components from svelte-routing. For each route, we want to use the Route component with a component prop, where we can pass the component that we want to render. Notice that Route components can only be ...