How to: Create a modern Javascript Router

Riccardo Canella
Javascript by doing
3 min readMay 6, 2019

--

Single page applications are everywhere around us, React-based, Vue or in vanillaJS. To have a good single page application you need to have a fantastic router mechanism. Library like navigo or react-router are really great. But how do they work? Do we really need to import the entire library? Or is it ok to just use a 10% of it? In general, creating a fast and useful router is very simple and requires little less than 100 lines of code.

Requirements

Our router should be:

  • Written in es6+
  • Compatible with history and hash routing
  • A reusable library

Let’s start to code

Generally only one instance of router is used for each webapp but there are many cases where it is necessary to have more than one, for this we will not implement a Singleton pattern. Our router need 4 basic properties to work:

  • routes: The list of registered routes
  • mode: hash or history
  • root: the root of the application if we are in history mode
  • constructor: a base function to create a new instance of the our Router

Adding and removing routes

Adding or delete a route will just push or delete an element from an array

Get the current path

We obviously need to know where we are in a specific moment in our application.

To do that we have to handle both cases, history mode and hash mode. In the first case we have to delete the root path from the window.location , in the latter we have to delete the “#” . We also need a function ( clearSlash )to delete the / from the start or from the end of the string to not limit the developer in route writing phase

--

--

Riccardo Canella
Javascript by doing

Riccardo Canella @ricanella92 Love #basket, #bike and #HIMYM since my childhood. #Fullstack #Javascript addicted - https://canellariccardo.it