verysimplerouter

A Javascript router featuring:

Usage no npm install needed!

<script type="module">
  import verysimplerouter from 'https://cdn.skypack.dev/verysimplerouter';
</script>

README

VerySimpleRouter

A Javascript router featuring:

  • Matching based on normal regular expressions
  • Named parameters
  • Named routes
  • Executing more than one callback per route, making it for example possible to secure an /admin/ path in just one place
  • Handling GET parameters

Examples

To use it, install it with npm and require it, or include the verysimplerouter script to your page (in that case a VerySimpleRouter global variable is created).

Basic example

This example matches /users, /users/12 and /users/45 and also /users?sort=asc but not /users/pete. It also specifies a fallback when no match is found (like in /users/pete).

var routes = [
  {
    route : "^/users/:id(\\d+)quot;,
    callback : function(args, getParams) {
      console.log("User " + args.id);
    }
  },
  {
    route : "^/usersquot;,
    callback : function() {
      console.log("All users");
    }
  },
  {
    route : "",
    callback : function() {
      console.log("No match found!");
    }
  }
];
VerySimpleRouter.init({
  rootPath : "",
  routes : routes
});
// Start listening to the popstate event
VerySimpleRouter.startListening();

Securing an admin area

This example shows how to secure all routes that fall in /admin. By returning true from the callback, the router will keep matching the routes below until it finds a match again. So when someone goes to /admin/users, first the route ^/admin\b matches and is executed and because we return true, the next route ^/admin/users$ is also executed. We also add a named route to the login page.

Note you have to escape backslashes!

var routes = [
  {
    route : "^/admin\\b",
    callback : function() {
      if (!user_is_logged_in()) {
        alert("Sorry, not logged in!");
        VerySimpleRouter.navigate(VerySimpleRouter.getRoute("login"));
        return false;
      }
      // By returning true, the router will keep on matching the routes below
      // until it finds a match.
      return true;
    }
  },
  {
    route : "^/admin/usersquot;,
    callback : function() {
      console.log("You are logged in and are allowed to see all users");
    }
  },
  {
    route : "/login",
    name : "login",
    callback : function() {
      console.log("Login please");
    }
  }
];
VerySimpleRouter.init({
  rootPath : "",
  routes : routes
});
VerySimpleRouter.startListening();

GET parameters

The matching of the routes is done by looking at the part without GET parameters. So for example the following route /users will match /users but also /users?sort=asc&active=true. The callback will receive the GET parameters as the second parameter:

{
  route : "^/admin/users/:id(\\d+)/ordersquot;,
  callback : function(args, query) {
    console.log("Orders of user id " + args.id);
    // For example called with /users/12/orders?sort=asc
    console.log("You want to sort " + query.sort);
    // You can also get the route by calling it on the VerySimpleRouter:
    console.log(VerySimpleRouter.getRoute());
    // Displays: route: "", query: {}
  }
}

Make sure to

  • escape the backslashes in the regular expressions in the routes
  • leave out the ^ and $ for named routes as this is implicitly added to the route
  • put your most specific routes first, as the first match is executed
  • return true in a callback to keep the route matcher keep on going
  • never add a trailing slash to the rootPath - if served from the document root you can leave it out and it will default to an empty string
  • call extractRoute(e.target.href) first when calling navigate() from an A onclick handler as the HREF attribute always returns an absolute path and we only want to know the path from the root.

Base href

If you don't want to specify absolute paths in your links, you can add a BASE element with an absolute path set in the HREF attribute. For example if you serve the website from http://localhost/somedirectory/ the HREF would be:

<base href="/somedirectory/">

Note the trailing slash!