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: