SustainableWWW Logo
Blog post image

How to implement routes in your Svelte web application using svelte-routing?

Speed and simplicity - the two most sought-after virtues anywhere you go. Our world today has become obsessed with doing things fast and with as simple steps as possible. With everything going digital, the responsibility falls on us developers to make them so. To build such applications, you need tools that aid this objective. And that’s why there is a new JavaScript framework every day.

Svelte, no doubt, is also one of them but with a very different approach to front-end development than seen in other frameworks. Svelte brings reactivity to JS itself and eradicates the need for a virtual DOM and boilerplate code. This is why Svelte is getting immensely popular among the dev community for building simple and fast web applications.

Today we are talking about Svelte and the most important concept in web development - routing. Let’s start off with the very basics.

What Is Routing In Web Development?

Routing, as we know it, is the whole crux of websites. Routes determine which code needs to run when a user visits a certain page. Let’s take an example to understand it more practically. Let’s say a user visits the following URL on a website:

https://your-site.com/example

As soon as the user hits this route, there will be a specific piece of code written for exactly this page. That piece of code will run and the user will be able to see the content of the page.

What Options Do We Have for Routing in Svelte?

Taking our focus to Svelte, routing is obviously needed when you go around building web apps using this framework. But there isn’t an official router available with the Svelte library. Although developers at Svelte are working on SvelteKit, it’s in the Beta testing stage at the time of writing and it’s not quite popular among Svelte coders.

The following four frameworks are most commonly used to implement routing in Svelte based on the specific use case:

Among these, svelte-routing is the one most commonly used with Svelte for routing because it is made particularly for Svelte and for routing in Svelte. It’s in the name!

What Is svelte-routing by npm?

svelte-routing is a routing library for Svelte that uses the declarative HTML approach for development. Just like Svelte, this library is easy to set up and use which makes it the library of choice for many of us. 

svelte-routing also has SSR (server-side rendering) support which provides you with several additional benefits for your websites. Performance and speed being the utmost benefits of SSR routing, svelte-routing also makes your app more secure and trustable for visitors. From a marketing perspective, it will also help you appear higher in the results when someone searches for your services or product since server-side rendered pages load faster and search engines prefer such pages. 

So because of all the benefits mentioned above and because it has the most weekly downloads on the npm website, svelte-routing is the library we will be focusing on in this tutorial.

The installation of svelte-routing is quite easy and can be easily done with npm. Simply run this command in the terminal:

npm install --save svelte-routing

Implementing Routing In Your Svelte Application Using svelte-routing

Now that the basics are covered, we can jump right into implementing routing in your Svelte app. Because I love blogs, we will be implementing routes to display a home page and a blog landing page. Let’s start with a basic Svelte app with only two files in the src folder - main.js and App.svelte. The former will have the below code while the latter will be empty for now.

import App from './App.svelte';
const app = new App({
   target: document.body,
   hydrate: true
});
export default app;

This file simply sets up the app constant for loading and displaying your web application. One interesting thing here is the hydrate option, this option tells Svelte to upgrade existing DOM (usually from SSR) rather than creating new elements. This option only works if the app is compiled with the hydratable option as true which you can set in rollup.config.js. Let’s get on with some code writing now.

First of all, we will put the code down to give content to our pages. Let’s make a folder named routes inside our src folder and put two files home.svelte and blog.svelte:

<h1> Hey! I am the Home! </h1>


<h1> Hey! I will show you all the blogs! </h1>

Now we want our App.svelte to show links to the above pages, we add the following code to it:

<script>
  import { Router, Route, Link } from "svelte-routing";
  import Home from "./routes/home.svelte";
  import Blog from "./routes/blog.svelte";

  export let url = "";
</script>

<Router url="{url}">
  <nav>
   <Link to="/">Home</Link>
   <Link to="blog">Blog</Link>
  </nav>
  <div>
   <Route path="/"><Home /></Route>
   <Route path="blog" component="{Blog}" />
  </div>
</Router>

So now I have got some explaining to do. The first three lines in the <script> tag above are importing needed components from the svelte-routing library and the pages we want to display.

  • Router - the Router component is responsible for handling everything by providing routing info to Link and Route components inside it. We need to have at least one Router in our app as it will pick the best Route to display when a visitor visits a particular URL.
  • Route - this specifies the actual route. Its two properties path and component decide which page to display when a certain path is hit.
  • Link - This works just like the <a> tag in HTML with the to property working as href.

The URL variable we have exported is used by SSR to force the current URL of the application and it is used by Link and Route components too.

After that, we have set up the look of our page by putting two links to our pages on it and have handled routing to those pages by the Route component.

Just one more file and we will be good to go - server.js that exists in the root of the application. This file is responsible for always rendering the application in index.html. Below is the code you need to add to this file:

const { createServer } = require("http");
const app = require("./dist/App.js");

createServer((req, res) => {
  const { html } = app.render({ url: req.url });

  res.write(`
   <!DOCTYPE html>
   <div id="app">${html}</div>
   <script src="/dist/bundle.js"></script>
  `);

  res.end();
}).listen(3000);

And that’s it. Let’s test the routes that we set up using svelte-routing. Simply reload the page. If you got a 404 message, don’t worry! You will have to simply add -single to the start property in your package.json. This will make sure that index.html is always served no matter which path you are on:

"start": "sirv public -single"

Reload now. Yus, it works now! Try navigating to /home and /blog route and see your pages in action!

The Disadvantage Of Traditionally Importing Routes

Congratulations! You have successfully set up routing in your Svelte app using svelte-routing. But there is a little problem with how your website works right now. 

When a user visits only one page of your website e.g. the home page, the code for the whole application is downloaded at their side. While this does not seem like a big problem right now, it will seriously affect the performance of your web app as you implement more functionality in it and the code base grows. Think of the overhead for downloading complete code even when the visitor doesn’t visit more pages!

Luckily, this is a fixable issue and the fix is called dynamic imports or code splitting. This technique splits up our code into multiple files and only downloads them once they are required. So the files for your blog page will only be downloaded when your visitor goes to read your articles and so on for all the pages. This considerably reduces the network load.

Let’s see how we can implement dynamic imports in our Svelte app.

Dynamically Importing Routes (Code Splitting) In Svelte

Below you can see a simple or traditional import for the About page in Svelte using <svelte:component> tag:

<script lang="ts">
   import About from "./Pages/About.svelte";
</script>

<svelte:component this={About}>

We can make this import dynamic by using onMount from Svelte which will make sure the About page is loaded only when the visitor lands on it. Below code will simply implement code splitting in your Svelte application:

<script lang="ts">
   import { onMount } from "svelte";
   import 404 from "./Pages/404.svelte";
   let About = null;

  onMount(async () => {
    try {
     About = (await import("./Pages/About.svelte')).default;
    } catch (e) {
     About = 404;
    }
  })
</script>

<svelte:component this={About}>

You can read a detailed tutorial that explains the implementation of dynamic importing in Svelte along with the relevant components used.

Concluding Thoughts

So this is a simple and easy way of implementing routing in your Svelte app using the svelte-routing library. We have also briefly touched upon dynamic imports in your code so you can build efficient and environment-friendly apps that use fewer resources to function. Hope this helps with your project!