Web Development

Svelte Routing with Page.js

June 9th, 2020 | By Ahmed Bouchefra | 4 min read

Today, we will teach you how to implement routing in our Svelte.js apps with the handy Page.js library.

In a previous tutorial, we created a simple news app to fetch data from a remote REST API and compared Svelte with React.

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

Prerequisites

To follow this tutorial, you should have the following:

  • Familiarity with JavaScript alongside HTML and CSS;

  • Both Node 8+ and npm are installed on your machine. You can use nvm (macOS or Linux) or nvm-windows to install and switch between Node versions on 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. 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 in various ways, such as:


We'll use Page.js to implement routing. This seems to be a 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"


To:

"start": "sirv public --single"


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

Creating Components

Let's now create a few components for 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 src/components/Home.svelte and update it as follows:

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

You can get your API key from the News API website. For more details about this code, explore the previous tutorial about the differences between Svelte and React.

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

<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, as well as the two Home and About components:

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

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

<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 tell Page.js to watch for changes to 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:

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

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

    export let params;

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


Conclusion

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, a popular choice among the growing Svelte community.

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

But regardless of the JavaScript framework used, 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.

Jscrambler

The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.

View All Articles

Must read next

Javascript

Optimizing Page Speeds With Lazyloading

We're going to explore the topic of lazy-loading Angular 2 modules and learn how we can set up our application to be as highly performant as possible.

January 2, 2017 | By Thomas Greco | 6 min read

Application Security

ICO Case Study | Tackling Cryptojacking with Real-time Webpage Monitoring

UK’s Information Commissioner’s Office (ICO) website was caught serving the CoinHive crypto miner to its users and it wasn't the only website affected. What could have been done?

February 14, 2018 | By Pedro Fortuna and Paulo Silva | 8 min read

Section Divider

Subscribe to Our Newsletter