Routing and navigation are critical components for building single-page applications (SPAs) in Svelte. While Svelte does not include a built-in routing library, the community provides several high-quality third-party libraries to meet routing needs. Among the most popular are svelte-spa-router, Routify, and svelte-routing.
svelte-spa-router
Installing svelte-spa-router
To use svelte-spa-router, first install it in your project directory by running:
npm install svelte-spa-router
Configuring Routes
You can configure routes in your main application component, typically App.svelte. Start by importing the Router and Route components.
<!-- App.svelte -->
<script>
import { Router, Route } from 'svelte-spa-router';
import Home from './Home.svelte';
import About from './About.svelte';
import Contact from './Contact.svelte';
</script>
<Router>
<Route path="/" view={Home} />
<Route path="/about" view={About} />
<Route path="/contact" view={Contact} />
</Router>
Navigation Links
To navigate within the application, use the Link component provided by svelte-spa-router.
<!-- Navigation.svelte -->
<script>
import { Link } from 'svelte-spa-router';
</script>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
Route Guards
svelte-spa-router supports route guards, allowing you to execute logic before route transitions, such as authentication checks.
<!-- App.svelte -->
<script>
import { Router, Route, before } from 'svelte-spa-router';
import Home from './Home.svelte';
import About from './About.svelte';
import Contact from './Contact.svelte';
before((to, from, next) => {
// Check authentication status here
if (!isAuthenticated()) {
next('/login');
} else {
next();
}
});
</script>
<Router>
<Route path="/" view={Home} />
<Route path="/about" view={About} />
<Route path="/contact" view={Contact} />
</Router>
Dynamic Routes
svelte-spa-router supports dynamic routes, enabling you to capture parts of the URL as parameters.
<!-- App.svelte -->
<script>
import { Router, Route } from 'svelte-spa-router';
import Post from './Post.svelte';
</script>
<Router>
<Route path="/post/:id" view={Post} />
</Router>
<!-- Post.svelte -->
<script>
export let id;
</script>
<article>
<h1>Post #{id}</h1>
</article>
In Post.svelte, the id variable is automatically populated with the value captured from the URL.
Nested Routes
You can implement nested routes, allowing multiple sub-routes under a parent route.
<!-- App.svelte -->
<script>
import { Router, Route } from 'svelte-spa-router';
import Dashboard from './Dashboard.svelte';
import User from './User.svelte';
</script>
<Router>
<Route path="/dashboard" view={Dashboard}>
<Route path="/dashboard/user/:id" view={User} />
</Route>
</Router>
Route Parameters and Query Strings
Route parameters and query strings can be accessed by components for use within the component.
<!-- Post.svelte -->
<script>
export let id;
export let query;
</script>
<article>
<h1>Post #{id}</h1>
<p>Query: {JSON.stringify(query)}</p>
</article>
In App.svelte, you can set it up like this:
<Route path="/post/:id" query={{ page: 1 }} view={Post} />
Routify
Routify is a popular Svelte routing library that provides a concise way to manage routing and navigation in Svelte applications. Routify supports dynamic routes, nested routes, lazy loading, preloading, server-side rendering (SSR), and more, making it an ideal choice for building complex SPAs and full-stack applications.
Installing Routify
Install Routify in your project using npm or yarn:
npm install @roxi/routify
# or using yarn
yarn add @roxi/routify
Configuring Routify
Routify’s configuration is primarily handled through file structure and conventions. Routify automatically scans the src/routes directory to build the routing tree.
- Each
.sveltefile is treated as a route. - Filenames can include dynamic parameters, e.g.,
user/[id].svelte. - Folders represent nested routes, e.g.,
admin/users/index.svelte.
Creating Route Files
Create route files in the src/routes directory. For example, you can set up the following structure:
src/
routes/
index.svelte
about.svelte
user/
[id].svelte
Using <Router> and <Route> Components
In your main application component, you can use Routify’s <Router> and <Route> components to render route views.
<!-- src/App.svelte -->
<script>
import { Router } from '@roxi/routify';
</script>
<Router />
However, Routify typically inserts the <Router> component automatically in src/main.js or src/main.ts, so you usually don’t need to add it manually in App.svelte.
Navigation Links
Routify provides a <Link> component to create navigation links easily.
<!-- src/components/Nav.svelte -->
<script>
import { Link } from '@roxi/routify';
</script>
<nav>
<ul>
<li><Link href="/">Home</Link></li>
<li><Link href="/about">About</Link></li>
</ul>
</nav>
Dynamic Routes
Dynamic routes allow you to capture parts of the URL as parameters. For example, user/[id].svelte captures 123 from /user/123.
<!-- src/routes/user/[id].svelte -->
<script>
export let id;
</script>
<article>
<h1>User ID: {id}</h1>
</article>
Nested Routes
Routify supports nested routes, allowing multiple sub-routes under a parent route.
<!-- src/routes/admin/users/index.svelte -->
<article>
<h1>Users List</h1>
</article>
Route Guards
Routify supports route guards, enabling you to execute logic before route transitions, such as authentication checks.
// src/routes/_guards.js
export default (to, from, next) => {
if (!isAuthenticated()) {
return next('/login');
}
next();
};
Reference the guard in a route file:
<!-- src/routes/user/[id].svelte -->
<script>
import _guards from '../_guards';
</script>
<!-- Other code... -->
SSR and Preloading
Routify supports server-side rendering and preloading, which are crucial for improving first-page load times and SEO.
Advanced Features
Routify offers advanced features like error handling, dynamic imports, and custom route resolvers.
svelte-routing
svelte-routing is another popular routing library designed for Svelte, particularly suited for applications requiring server-side rendering (SSR). It provides a simple yet powerful API for handling both client-side and server-side routing.
Installing svelte-routing
Install svelte-routing in your project using npm or yarn:
npm install svelte-routing
# or using yarn
yarn add svelte-routing
Setting Up Routes
svelte-routing uses <Router> and <Route> components to set up routes. Import these components in your main application component.
<!-- src/App.svelte -->
<script>
import { Router, Route } from 'svelte-routing';
import Home from './Home.svelte';
import About from './About.svelte';
import Contact from './Contact.svelte';
</script>
<Router>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Router>
Using the Link Component
svelte-routing provides a <Link> component for creating navigation links within the application.
<!-- src/components/Navigation.svelte -->
<script>
import { Link } from 'svelte-routing';
</script>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
Dynamic Routes
Dynamic routes allow you to capture parts of the URL as parameters, such as for displaying user profiles.
<!-- src/App.svelte -->
<script>
import { Router, Route } from 'svelte-routing';
import UserProfile from './UserProfile.svelte';
</script>
<Router>
<!-- Other routes... -->
<Route path="/user/:id" component={UserProfile} />
</Router>
<!-- src/components/UserProfile.svelte -->
<script>
export let id;
</script>
<article>
<h1>User Profile: {id}</h1>
</article>
Nested Routes
svelte-routing supports nested routes, allowing you to define multiple sub-routes under a parent route.
<!-- src/App.svelte -->
<script>
import { Router, Route } from 'svelte-routing';
import Admin from './Admin.svelte';
import AdminUsers from './AdminUsers.svelte';
</script>
<Router>
<Route path="/admin" component={Admin}>
<Route path="users" component={AdminUsers} />
</Route>
</Router>
Route Guards
svelte-routing supports route guards, enabling you to execute logic before a route change, such as authentication checks.
// src/guards/authGuard.js
export default function (to, from, next) {
if (!isAuthenticated()) {
next('/login');
} else {
next();
}
}
Use the guard in a route:
<!-- src/App.svelte -->
<script>
import authGuard from './guards/authGuard';
</script>
<Router>
<Route path="/admin" component={Admin} beforeEnter={authGuard} />
</Router>
Server-Side Rendering
svelte-routing supports server-side rendering, which is essential for SEO and performance optimization. You can use its middleware on the server to handle routing.
Advanced Features
svelte-routing offers advanced features like redirects, error handling, and lazy loading.



