Arrow keys: ← previous · → next 32 of 37
@nodedk/router
0.2.0 stable isomorphic

Router#

Standalone pathname matching and request routing for NodeJS.

Install#

npm i @nodedk/router

Usage#

var router = require('@nodedk/router')

var routes = [
  { name: 'home', paths: '/' },
  {
    name: 'product',
    paths: ['/product/:slug', '/products/:slug']
  }
]

var matcher = router(routes)
var route = matcher('/product/panel-heater')

if (route) {
  console.log(route.name) // 'product'
  console.log(route.matches.slug) // 'panel-heater'
}

router(routes) prepares the routes once and returns a reusable matcher. matcher(pathname) returns { name, matches }, or null when nothing matches. name is optional and omitted from the result when not supplied. Exact paths take precedence over dynamic paths. Otherwise, the first matching route and path wins. Exact matches have an empty matches object.

paths accepts a string, an array of alternatives, or a language-keyed object:

var routes = [
  { paths: '/article/:slug' },
  { name: 'product', paths: ['/product/:slug', '/products/:slug'] },
  { name: 'contact', paths: { en: '/contact', no: '/kontakt' } }
]

var matcher = router(routes)
var route = matcher('/article/hello')
// { matches: { slug: 'hello' } }

Routes can also be a name-keyed object, with each key supplying the route name. The standalone API matches pathnames only; it does not filter HTTP methods or mutate the route definitions. Pass the URL pathname, without a query string.

Multiple dynamic parameters#

Prefix each dynamic segment with : and use distinct parameter names. Each parameter matches one non-empty path segment.

var routes = [
  {
    name: 'product',
    paths: '/category/:category/product/:slug'
  }
]

var matcher = router(routes)
var route = matcher('/category/heaters/product/panel')
// {
//   name: 'product',
//   matches: { category: 'heaters', slug: 'panel' }
// }

Request-based API#

The existing router(routes)(req) API remains available. It sets req.route and req.matches on a request containing pathname and method.

var resolve = router([
  { name: 'product', paths: '/product/:slug', method: 'GET' }
])

var req = { pathname: '/product/panel-heater', method: 'GET' }
resolve(req)

req.route.name // 'product'
req.matches.slug // 'panel-heater'

Created by Eldøy Tech AS

Tools for business systems.