What is HTTP router and how to build simple router in isomorphic JavaScript applications?

Routing, often known as an HTTP router, is a technique that directs HTTP requests to the code that is responsible for handling them. To put it more simply, the HTTP router is where it’s decided what actions should be taken when a user accesses a particular website.

Numerous routing libraries are already built and ready to be used, making it simple to add new routes to your application without manually creating each one. For example, Router is a JS router that can work either on the client side (in the browser) or on the server side. It’s responsible for resolving URL paths to route patterns and producing params objects sent along to each route.

If HTTP requests are routed, the Router offers certain fundamental web server functionality, such as “parses req.body into params.”

Features

  • Easy setup, zero dependencies
  • Only 2kb minified and gzipped
  • Simple syntax and usage
  • Works client-side as a router for single-page applications (SPAs)
  • Works server-side as a router for an HTTP server 
  • Works in the terminal as an args parser for command-line programs

Basic syntax example

router({

 ‘/home’:                  (params) => { … },

‘/profile/:id’:           (params) => { … },

 ‘/profile/:id/user/:uid’: (params) => { … },

});

Steps to building a simple router for isomorphic JavaScript applications

Building an HTTP router requires two files:

  • index.html
  • script.js

Once you have those, follow the eight steps below to build your router for isomorphic JavaScript applications. 

Step1: Create a div in index.html with the id “app” and place it there. Add the script.js file as a link.

<div id=”app”></div>

<script src=”./script.js”></script>

Step 2: Create two objects in your script.js file to hold the routes and the template functions which will be rendered. 

let routes = {};

let templates = {};

Step 3: Then, make a home page function and an about function. These methods could be defined using arrow functions or ordinary functions.

let app_div = document.getElementById(‘app’);

function home() {

    let div = document.createElement(‘div’);

    let link = document.createElement(‘a’);

    link.href = ‘#/about’;

    link.innerText = ‘About’;

    div.innerHTML = ‘<h1>Home</h1>’;

    div.appendChild(link);

    app_div.appendChild(div);

};

function about() {

    let div = document.createElement(‘div’);

    let link = document.createElement(‘a’);

    link.href = ‘#/’;

    link.innerText = ‘Home’;

    div.innerHTML = ‘<h1>About</h1>’;

    div.appendChild(link);

    app_div.appendChild(div);

};

Step 4: Following that, we will define the routes. A path and a template that will be rendered together define a route. The name of a file or a function that creates DOM elements can be considered a template.

function route (path, template) {

    if (typeof template === ‘function’) {

        return routes[path] = template;

    }

    else if (typeof template === ‘string’) {

        return routes[path] = templates[template];

    } else {

        return;

    };

};

Step 5: The next thing to do is to set up the function that will act as the template engine.

function template (name, templateFunction) 

{

 return templates[name] = templateFunction;

};

You are now able to map a template to a route.

template(‘home’, function(){

    home();

});

template(‘about’, function(){

    about();

});

Step 6: The next step is to map out the route to templates.

route(‘/’, ‘home’);

route(‘/about’, ‘about’);

The template names are then matched with the names of the functions that generate and append the DOM elements to the app div.

As we can see in the examples below, the correct template may be rendered by simply detecting and resolving the changes in the URL.

function resolveRoute(route) {

    try {

        return routes[route];

    } catch (e) {

        throw new Error(`Route ${route} not found`);

    };

};

Step 7: In order to retrieve the route from the URL hash and then run the template function, you need to make a router function.

function router(evt) {

    let url = window.location.hash.slice(1) || ‘/’;

    let route = resolveRoute(url);

    route();

};

Step 8: Listening to the load and hashchange events will allow you to toggle between views. The load event is triggered when the page is fully loaded.

Alternatively, when a URL’s hash changes, an event called “hashchange” is triggered.

window.addEventListener(‘load’, router);

window.addEventListener(‘hashchange’, router);

The basic router is now ready. Your homepage should load automatically when you navigate to the index.html file in your browser. You should be sent to that section if you click the “about” link.

Final word on routers built in isomorphic Javascript applications

Hopefully, this guide will help you better understand the concept of Router in JS and how to use it so that your website functions as smoothly as it can. Routing libraries that already exist make it much easier to use Router than you may think.

Start using evisio today at no cost.

Complete access without commitment.

Try evisio FREE for 7 Days

What evisio is all about

Evisio helps agencies, marketers, and SEO consultants get results, no matter their level of SEO knowledge. It takes the guesswork out of SEO by telling you exactly what to do to improve your rankings and makes SEO simple by bringing all the parts of your SEO process together in one place.