DEV Community

Cover image for Svelte Routing with Page.js
Jscrambler for Jscrambler

Posted on • Originally published at

Svelte Routing with Page.js

In this article, we'll learn about how to implement routing in our Svelte.js apps.

In a previous tutorial, we have created a simple news app that fetches data from a remote REST API and we even compared it with React.

Let's now see how to add routing to that Svelte app.


In order to follow this tutorial, you should have:

  • Familiarity with JavaScript alongside with HTML and CSS;
  • Both Node 8+ and npm installed on your machine. You can use nvm (macOS/Linux) or nvm-windows to install and switch between Node versions in your system.

Initializing our Svelte App

Head over to your terminal and run the following command:

npm install -g degit

Next, initialize a new app using the following commands:

npx degit sveltejs/template sveltenewsapp
cd sveltenewsapp 
npm install 
npm run dev

You can access the app from the http://localhost:5000/ address.

Next, let's see how to implement routing in our Svelte application.

How to Add Routing to Svelte.js

You can add routing to your Svelte app using various ways such as:

We'll use Page.js to implement routing in this article. This seems to be a highly popular choice among Svelte developers mainly due to its high configurability.

Installing Page.js

We will get started by installing Page.js in our project.

Head back to your terminal, make sure you are inside the folder of your Svelte app and run the following command:

npm install page

Next, open the package.json file and change:

"start": "sirv public"


"start": "sirv public --single"

This will make sure we don't get any errors when navigating to routes from the browser's address bar.

Creating Components

Let's now create a few components in our application,

First, create a components/ folder in the src/ folder. Next, create two files, Home.svelte and About.svelte, inside the src/components/ folder.

Now, open the src/components/Home.svelte and update it as follows:

    import { onMount } from "svelte";

    const apiKEY = "YOUR-API-KEY";
    const dataUrl = `${apiKEY}`;
    let items = [];
    const fetchData = async () => {

        const response = await fetch(dataUrl);
        const data = await response.json();
        items = data["articles"];


<div class="container">

        {#each items as item}
            <div class="card">
                <img src="{item.urlToImage}">
                <div class="card-body">
                    <p> {item.description} </p>
                    <a href="{item.url}">Read</a>


h1 {
    color: purple;
    font-family: 'kalam';
.container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
    grid-gap: 15px;
.container > .card img {
    max-width: 100%;

Try Jscrambler For Free

You can get your own API key from the News API website.

For more details about this code, refer to the previous tutorial.

Next, open the src/components/About.svelte file and update it as follows:


<div class="container">
    This is a news app created with Svelte


Integrating Page.js with Svelte.js

Now, let's see how to use Page.js with Svelte.

Open the src/App.svelte file and import the router from the page package, and also the two Home and About components:

import router from "page"
import Home from './components/Home.svelte'
import About from './components/About.svelte'    

Next, define a page variable that will hold the matched component:

// [...]

let page


After that, define the routes of your application and call the start method of the router to start watching the changes on the URL:

// [...]

router('/', () => page = Home)
router('/about', () => page = About)



We created two routes for the Home and About components.

We passed, to the router function, the path as the first property and an arrow function to assign the matched component to the page variable as the second property. This will simply tell Page.js to watch for the changes on the URL in the browser and set the appropriate component as we specified.

Finally, we need to tell the router where to insert the matched component using the following code:

    Daily News

<svelte:component this={page} />

This should be added after the closing </script> tag.

You can now visit the / and /about paths to see the corresponding pages.

You can also use parameters with routes. For example, let’s suppose we want to be able to access a single article by its ID; you can do something like the following:

let params;
router('/article/:id', (ctx, next) => {
    params = ctx.params
    next()},  () => page = Article)

Where the ID is the parameter and the Article is a component that will be rendered when users visit routes such as /article/1.

In the Article component, we can access the ID parameter using the following code:

    import { onMount } from "svelte";

    export let params;

    const getID = async () => {



In this article, we have implemented routing in our Svelte app using the Page.js library.

We have built this on top of our previous tutorial where we created a simple news application. Here, we refactored the app to have two pages routed using a client-side JavaScript router available from Page.js, which is a popular choice among the growing Svelte community.

Have you given Svelte a try yet? If not, it may be worth a go!

But regardless of the JavaScript framework you're using, you should always protect its source code to avoid reverse-engineering and code tampering. See our tutorials on protecting React, Angular, Vue, React Native, Ionic, and NativeScript.

Originally published on the Jscrambler Blog by Ahmed Bouchefra.

Top comments (0)