Lightweight Route Recognizer

0.3.4 · abandoned · verified Sun Apr 19

route-recognizer is a compact JavaScript library (under 2KB) designed solely for matching paths against a set of registered routes. It functions as a low-level primitive for more comprehensive routing systems, such as `router.js`, which was notably used by Ember.js. Currently at version 0.3.4, last published in 2018, the library offers stable functionality for static, dynamic (e.g., `:id`), and wildcard (e.g., `*path`) segments. Its core differentiator is its minimalistic approach, focusing exclusively on route recognition and parameter extraction without handling routing logic, history, or view rendering. The package ships with TypeScript types, but its development status appears to be unmaintained given the last commit and release dates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate RouteRecognizer, add various route patterns including dynamic and star segments, and then use the `recognize` method to match paths and retrieve associated handlers and parameters.

import RouteRecognizer from 'route-recognizer';

const router = new RouteRecognizer();

const postsHandler = (params) => `Handling posts with params: ${JSON.stringify(params)}`;
const singlePostHandler = (params) => `Handling single post with ID: ${params.id}`; 
const adminHandler = () => `Admin section accessed`;
const pageHandler = (params) => `Serving page: ${params.path}`;

router.add([{ path: "/posts", handler: postsHandler }], { as: "allPosts" });
router.add([{ path: "/posts/:id", handler: singlePostHandler }], { as: "singlePost" });
router.add([ { path: "/admin", handler: adminHandler }, { path: "/posts", handler: postsHandler } ], { as: "adminPosts" });
router.add([{ path: "/pages/*path", handler: pageHandler }], { as: "catchAllPages" });

let result = router.recognize("/posts");
console.log("Recognizing /posts:", result?.[0]?.handler(result?.[0]?.params));

result = router.recognize("/posts/123");
console.log("Recognizing /posts/123:", result?.[0]?.handler(result?.[0]?.params));

result = router.recognize("/admin/posts");
console.log("Recognizing /admin/posts:", result?.[1]?.handler(result?.[1]?.params));

result = router.recognize("/pages/about/us");
console.log("Recognizing /pages/about/us:", result?.[0]?.handler(result?.[0]?.params));

view raw JSON →