JS Funda: Client-Side Routing and The History API

Mayank Chaudhari
6 min readSep 17, 2022

--

Client-side routing makes your page transitions smooth like cutting butter

Ever wondered how popular front-end frameworks and libraries like Nuxt.js, Next.js, Angular, Vue Router, React Router, etc. handle SPAs (Single Page Applications) and make page transitions quick and efficient? And can you do the same using vanilla JS?

If you are interested in mastering the modern web frameworks, check out my courses here and avail great discounts and offers. You might get some for FREE as well.

Here in this post, we will see what client-side routing is and a crude way of creating your own client-side routing mechanism. This will help you understand the essential principle behind client-side routing.

First of all, what do we mean by routing in the context of a website or a web app? It simply means moving (routing) from one page to another page. Depending on the mechanism used for this routing, it may be called, server-side or client-side routing.

What Is the Difference Between Server-Side and Client-Side Routing?

Client-side routing is similar to server-side routing; however, it is performed in the browser.

A typical web application contains numerous pages that map to different URLs, and each page contains some logic and a template that is then rendered.

Client-side routing simply executes this procedure in the browser, employing JavaScript for logic and a JS-based template engine or other similar ways to render the pages.

It’s most commonly used in single-page apps, where the server-side code is largely utilized to provide a RESTful API that the client-side code consumes through Ajax.

Server-side routing

In server-side routing, a user clicks a link that requests a new page or new data from the server (another computer). The user is then served new data or documents.

Let’s break this down even further:

When a user clicks on a link on a website, another entire page is loaded and displayed on the screen. The URL route is modified to reflect the user’s current location on the web page.

The server is responsible for loading and rendering the “whole page.” Because we are making another request to our server, which is supplying us with a whole new page to display, server-side routing causes the entire page to refresh.

The biggest disadvantage of adopting server-side routing is the variable time it takes for content to appear on a page. Why would we need to reload this information if the page the user is accessing would still display that header and footer information?

However, the server is unaware that we do not need to reload that information because it is already presented. The server will return the file that needs to be displayed and then request a full refresh to display the new file.

With the entire refresh, we can now factor in internet speeds. Internet speeds influence how long it takes for things to appear on a page.

But how can we prevent this complete page refresh and possibly speed up our render process? That is done using JavaScript through Client-side routing.

Client-side routing

Client-side routing is the internal handling of a route that is delivered to the front end within your JS file (or client).

Because of the popularity of constructing single-page applications, more developers are considering client-side routing while developing their apps (SPAs).

When a user clicks on an internal link within your application, the goal of a Single Page App is to notice a change in the URL bar to indicate that the page is being updated without a full-page refresh.

We don’t need several pages to load with a SPA, simply the original request with our initial HTML, CSS, and JS files from the server. As a result, client-side routing is employed to generate that SPA experience while also making our users’ paths more standard and organized.

The routing is intended to provide a better overall experience for our visitors by allowing them to pinpoint where they are in the application using the route in the URL bar, all without requiring us to make repeated server queries.

Advantages of Client-side Routing

We are concerned about client-side routing for several reasons:

  • It provides the user with a URL that makes more natural sense for them to see where they are in your application.
  • Using the history API, we want to give the user the opportunity to use the “back” and “advance” buttons in their browser.
  • It allows the user to key in a specific URL and have the application load that specific view.
  • Because the information required to render the next view was already loaded during the original page load, the application will have less lag time between various links.

Now that you understand well what client-side routing is and its advantages, let us discuss how it can be achieved using vanilla JS.

The History API

There are several ways you can update the URL using JavaScript. One of them is using the location property.

location.href = 'your-new-url'

But this will cause the page to reload. And remember, for client-side routing, for the efficient utilization of resources and enhanced user experience, we don’t want to reload the entire page. There comes the history API.

The history API is a collection of methods on the history object that can be used to manipulate the browser’s history (the stuff accessed by the forward and backward buttons). It is supported by all modern browsers and on all major platforms.

The `history.pushState() ` Method

The history.pushState() method can be used to insert a new item into the browser’s history and, as a result, update the displayed URL without refreshing the page. It accepts three arguments:

  • state, an object containing information about the URL or an item in the browser’s history
  • title, which is supposed to be what the document is about.
  • url, the URL to add to the browser’s history.

This strategy is especially useful for single-page apps if you wish to load content with JavaScript but change the URL to match.

Assume you were on the homepage and wanted to update the URL to match the about page. You may try something like this:

history.pushState(‘about,’ ‘About,’ ‘/about’);

You learned how to pushState to history without reloading the page. However, you also need to detect when a user changes the history by pressing forward or backward browser buttons. Let’s look at the popstate event.

The history object provides a few more helpful methods for navigation such as history.back() to go back (load the previous URL), history.forward(), and history.go().

history.go(-2) // will take you 2 steps back, if available

The popstate event

If you use history.pushState() to update the URL, the URL will change when the user hits the forward or backward buttons, but the UI will not. Thus, you need to use the popstate event to detect URL changes and execute necessary UI modifications.

window.addEventListener('popstate', function (event) {
// The URL changed...
});

Now, you know pretty much how you can utilize vanilla JS to manipulate URLs and UI to create a client-side routing experience.

If you are interested in learning modern web frameworks, modern JS and TypeScript, do enroll in my courses available on Udemy.

Happy Coding!

--

--

Mayank Chaudhari

Technical Writer | Developer | Researcher | Freelancer | Open Source Contributor