Let’s code a client side router for your frameworkless SPA
Tags: javascript, frontenddevelopment, clientsiderouter, javascriptframework
Published: 2019-05-24 19:12:40

---
title: Let’s code a client side router for your frameworkless SPA
published: true
description: A tutorial on building javascript router
tags: javascript, frontend development, client side router, javascript framework 
---

!["Photo by Jordan Ladikos on Unsplash"](https://cdn-images-1.medium.com/max/1500/1*XsdtxKTqZPC7DTtzLBEgfA.jpeg)


Yes, you read the title right, Client side router for a frameworkless SPA, that’s exactly what we are going to build in this story.

<hr>

Before we dive into the code, let’s first understand what is client side routing.

A client side router runs on the user’s browser. The browser does not make a request to the server for the page, rather it looks into the JavaScript code that is loaded onto the browser to render the page for the matched route.

This is how our router would render the page — 
1. Listen on hashchange event.
2. When the url changes, match and parse the url to the route predefined in the code.
3. Look for the view to be rendered for that route, if no match is found render a 404 message.

![](https://cdn-images-1.medium.com/max/1000/1*9ntD58Eb0tHhvcuOwUC7fQ.jpeg)

**Enough theory, show me the code already!**

<hr>

Below is the folder structure that we’d be working with

![](https://cdn-images-1.medium.com/max/1000/1*hp_m21itclu4CkEgLMj_Ow.png)

Let’s define a class to represent the Route in the router folder.

![](https://cdn-images-1.medium.com/max/1500/1*7fAYkPLx6KQo4Y1YU4T0Wg.png)

The Route class would take in 3 parameters while instantiating; name, path and the view associated to the route.

The setProps() method will set the props or properties that would be passed on to the route from the url and the renderView() method would return the view of the route.

![](https://cdn-images-1.medium.com/max/1500/1*yeqz__GDjOxGuDeS6wdQVA.png)

The Router class will be the heart of our routing system. It will take an array of route objects as the first parameter and the renderNode where the view will be injected as the second.

Our Router class will have methods like match() and navigate() to match the routes and navigate respectively. Lets look at their definitions.

![](https://cdn-images-1.medium.com/max/1500/1*knwAYtBoAzPZv0v7tf7o4w.png)

The navigate() method will filter through each route and check if it matches with any of the predefined routes. If no route is matched the renderNode will render a 404 message, else it would render the matched route’s view;
In the match(), we are creating regular expression of the route path and matching it with the requested path. If it matches we are also finding out if the requested route has any route parameters.

Well you might have already noticed the problem in the navigation(), we are literally injecting the view using innerHTML, which btw must be avoided at all cost. Mainly because of security reasons regarding XSS and also another problem that I encountered while coding, that any element in the injected view does not have an event listener attached to it. So that means you cannot have a button in a view to navigate to another route, it simply won’t work. To get around this we need to build the view using document.createElement(). To keeps this post concise, I’m leaving it upto you to figure it out(I may explore it later).

I like to add utility functionalities so lets define another method to add routes to the router.

![](https://cdn-images-1.medium.com/max/1500/1*7MKnCbvmD6lrozOFktDohA.png)

Let’s take a look at the index.js of router.

![](https://cdn-images-1.medium.com/max/1500/1*Ka8fMeFz1XbKV8p2sFO72Q.png)

Here we are exporting a function which takes routes as the parameter and creates an instance of the Router Class. The renderNode is a div with an id of app. We are adding the click event listener to the buttons that have a route attribute (inspired from other libraries), and listening for the hashchange event on the url to call the navigate() method.

Now, lets take a look at all the views in the application (look at the captions if you get lost keeping tracks of files)

![](https://cdn-images-1.medium.com/max/1500/1*SIoXdaag6fKEERNjJFm6JQ.png)

![](https://cdn-images-1.medium.com/max/1500/1*efpgntCNeD3sAkd86DgiWw.png)

![](https://cdn-images-1.medium.com/max/1500/1*24Tr_XCNYltCn-Pz_ZrhgA.png)

![](https://cdn-images-1.medium.com/max/1500/1*vGO31jw1iMUvu-B9HA2-LA.png)

You can install html pragmas in your code editor for syntax highlighting the html in template literals.

And finally in our app.js file lets define all our routes and pass it to our router.

![](https://cdn-images-1.medium.com/max/1500/1*XeyYB6XCEhgVqduVr2GsYw.png)

The following code would go in the body of the index.html file

![](https://cdn-images-1.medium.com/max/1500/1*Zj2wL9El6b9AxNwry0Lx7w.png)

Make sure to add the type=”module” in the script tag in order to use the import/export es6 feature, because of this we don’t have to setup any extra configuration.

To wrap this up lets add a few lines of CSS.

![](https://cdn-images-1.medium.com/max/1500/1*VFmylzBVlVMjurDiBdz6VQ.png)

To conclude this post, I’d say that you don’t need to bring in other libraries for small and simple Single Page Application, you can spin up you own custom solution, I just happen to show you one of the many ways, probably you can do more and much better. If you do, do let me know, I’d be happy to see your work.

I referred to this video on YouTube for writing the story — https://www.youtube.com/watch?v=D1fLaNxd-ZM

<hr>

You can take a look at the final repo in my [github](https://github.com/vijitail/simple-javascript-router), if you get stuck while following along. You can DM me on instagram [@vijit__ail](https://instagram.com/vijit__ail) if you come across any problem.

Cheers and happy coding 🍻😉

<i>This post was originally shared on medium. Check out my medium profile [@vijit2ail](https://medium.com/@vijit2ail)</i>