Skip to content

Instantly share code, notes, and snippets.

@noygal
Last active February 17, 2018 22:00
Show Gist options
  • Save noygal/fca0125213530b7893c8fcc1fa5c7a09 to your computer and use it in GitHub Desktop.
Save noygal/fca0125213530b7893c8fcc1fa5c7a09 to your computer and use it in GitHub Desktop.
Blog post

50 lines of code: build your own frontend router

Motivation

So, you want to add url routing to your web application, you open up your trusted browser, type "[react|angular|vue.js|etc'] router", review the router libraries for your framework/library and choose which one to use. Well great, you did what most web developers would do, but by doing so you've most likely bonded you logical code to your view code.

If you simplify routing operations then yes, it can be considered as a view level operation, but as routing operations usually requires some sort of logical/business flows for loading resources or dependencies, something you expect to be in a controller. In some cases (mostly frameworks such as angular) mixing those two is not considered by itself as bad practice, but with the modern view only libraries (such as react) this binding prevent you from creating a true separation between your view library and the rest of you code.

On my last UI project, a small scale backoffice inhouse/internal react based web application, I chosen to try to build up my own minimal url router module by using a few simple libraries. My requirements were simple:

  1. Basic url routing functionality.
  2. Support for path and query parameters - for easy way to preserve state on the url (great for sending dev links).
  3. Event emitter/observable for url and parameters changes.

Choosing my tools

Routing

As I was searching for basic router library I came across this article, which lead me to navigo - a routing library that in 500 lines of code pretty much cover all your demand from a router library. The only missing part was automatic url query parsing/constructing (navigo uses strings), but there always query-string for that.

Event emitting

freezer-js - minimal and powerful immutable/observable state library, I mostly use it on small single state project, seem to fit this case.

To the Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment