Let’s code a client side router for your frameworkless SPA

Vijit Ail
The Startup
Published in
7 min readMay 19, 2019

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.

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 or custom event in case of history.pushState().
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.

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

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

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

router/Route.js

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.

router/Router.js

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.