Svelte Routing with Page.js
Tags: svelte, javascript, routing
Published: 2020-06-12 16:41:53

---
title: Svelte Routing with Page.js
published: true
description: Svelte is the up-and-coming framework in the JavaScript ecosystem. Let's learn how to set up routing using the handy Page.js library.
tags: Svelte, JavaScript, Routing
canonical_url: https://blog.jscrambler.com/svelte-routing-with-page-js/
cover_image: https://blog.jscrambler.com/content/images/2020/06/jscrambler-blog-routing-svelte-pagejs.jpg
---

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

In a previous [tutorial](https://blog.jscrambler.com/svelte-vs-react-differences-when-building-the-same-web-app/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing), 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.

## Prerequisites

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](https://github.com/creationix/nvm#installation)  (macOS/Linux) or  [nvm-windows](https://github.com/coreybutler/nvm-windows#node-version-manager-nvm-for-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:

```bash
npm install -g degit
```

Next, initialize a new app using the following commands:

```bash
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:

 - Using [Sapper](https://sapper.svelte.dev/), a framework built on top of Svelte by the Svelte team;
 - Use community packages like [svelte-routing](https://github.com/EmilTholin/svelte-routing) or [Page.js](https://visionmedia.github.io/page.js/).
 
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:

```bash
npm install page
```

Next, open the `package.json` file and change: 

```json
"start": "sirv public"
```

To:

```json
"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:

```html
<script>
	import { onMount } from "svelte";
    
	const apiKEY = "YOUR-API-KEY";
	const dataUrl = `https://newsapi.org/v2/everything?q=javascript&sortBy=publishedAt&apiKey=${apiKEY}`;
    let items = [];
	const fetchData = async () => {

    
    	const response = await fetch(dataUrl);
    	const data = await response.json();
		console.log(data);
    	items = data["articles"];
    };
    
	onMount(fetchData());
	
</script>
<div class="container">

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

</div>

<style>
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%;
}
</style>
```

<a href="https://jscrambler.com/signup?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing" target="_blank" class="free-trial-ad"><img alt="Try Jscrambler For Free" src="https://media.jscrambler.com/blog/V1-freetrial.jpg"></a>

You can get your own API key from the [News API website](https://newsapi.org/).

For more details about this code, refer to the previous [tutorial](https://blog.jscrambler.com/svelte-vs-react-differences-when-building-the-same-web-app/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing).

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

```html
<script>	
</script>

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

<style>
</style>
```

## 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: 

```html
<script>
import router from "page"
import Home from './components/Home.svelte'
import About from './components/About.svelte'    
</script>
```

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

```html
<script>
// [...]

let page

</script>
```

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

```html
<script>
// [...]

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

router.start()

</script>
```

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:

```html
<h1>
	Daily News
</h1>

<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:

```js
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:

```js
<script>
    import { onMount } from "svelte";

    export let params;

    const getID = async () => {
        console.log(params.id);
    };
    onMount(getID());
	
</script>
```

## Conclusion

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 <a href="https://blog.jscrambler.com/protecting-your-react-js-source-code-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">React</a>, <a href="https://blog.jscrambler.com/how-to-protect-angular-code-against-theft-and-reverse-engineering/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">Angular</a>, <a href="https://blog.jscrambler.com/how-to-protect-your-vue-js-application-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">Vue</a>, <a href="https://blog.jscrambler.com/how-to-protect-react-native-apps-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">React Native</a>, <a href="https://blog.jscrambler.com/protecting-hybrid-mobile-apps-with-ionic-and-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">Ionic</a>, and <a href="https://blog.jscrambler.com/protecting-your-nativescript-source-code-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing">NativeScript</a>.

---

Originally published on the [Jscrambler Blog](https://blog.jscrambler.com/svelte-routing-with-page-js/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-routing) by Ahmed Bouchefra.