by JavaScript Teacher @ FreeCodeCamp

When you think of routers you usually think of libraries like React. But under the hood these libraries and frameworks still use vanilla JavaScript. So how do they do it? I hope this JavaScript router tutorial will help you understand how to put your own vanilla JS router together.

I've met plenty of people who wanted to create their own router for various reasons. After all, you searched for this vanilla JS router tutorial – that means you're looking to build one!

Bottom line, using a vanilla JS router reduces your dependency on frameworks.

Creating your own router in vanilla JavaScript is relatively easy as long as you understand all of the separate parts involved in making it.

Here are the key things to know about making your own JS router:

  1. The key to vanilla JS routing is the location.pathname property.
  2. Listen for the "popstate" event to respond to .pathname changes. This happens whenever a new URL is typed into browser's address bar but we don't want to refresh the page, but simply refresh the view by loading new content.
  3. You can optionally store routes in a routes[] array.
  4. Knowledge of JavaScript Regular Expressions (RegEx) to parse the URL is necessary.
  5. Basic understanding of history and history.pushState (JavaScript's History API) is critical if you wish to integrate your router into native browser architecture.

I plan on building this tutorial over time because I'm learning as I'm writing it myself. First, we'll tackle the History API.

A quick review of JavaScript History API

I've seen so many vanilla JS router tutorials that don't mention JavaScript's History API. Too bad, because clicking the browser's Back and Forward buttons has everything to do with navigating between URLs in browsing history. You can't speak about routing without the History API.

  1. history.back() is the same as history.go(-1), or when user clicks Back button in their browser. You can use either method to the same effect.
  2. history.forward() executes when user presses the browser's Forward button, and it is equivalent to history.go(1).
  3. go() is similar to .back() and forward() methods, except you can specify how many steps back or forward you want to go within the browser history stack.
  4. pushState() will push new state to the History API.
  5. .length property is the number of elements in the session history.