npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-proxy-router

v0.2.1

Published

A reverse proxy / router in node

Downloads

1

Readme

Router Build Status Coverage Status

The router acts as a reverse proxy from defined rules to specified endpoints.

Type of Routes

Routes are matched against all parts of a HTTP request. Currently implemented are

  • Path
    • STRICT - an exact match to the corresponding path
    • REGEX - a regular expression match
  • Header matches
    • detect AJAX requests
  • Method matches
    • GET, POST ...

Simple Example

To get the proxy running is straight forward.

var NodeProxyRouter = require('node-proxy-router')
var router = new NodeProxyRouter.Server()

router.addRoute('/mytarget', 'http://domain.tld/')

router.listen(3000)

Defining routes

STRICT Path routes

The router offers addRoute(path, endpoint, id = '', method = null, filters = []) to add simple strict routes. Path and endpoint are mandetory.

router.addRoute('/mytarget', 'http://domain.tld', 'root') // root page
router.addRoute('/mytarget/register', 'http://domain.tld/register', 'register', 'POST') // just handle POST requests for /register

REGEX Path routes

Always be aware, that REGEX routes are the slowest ones, cause they can't take advantage of the radix tree in the background. The router will loop over every single regex route to find a match. The interface looks like addRegexRoute(path, endpoint, id = '', method = null, filters = []), path and endpoint are mandetory.

router.addRegexRoute('^/mytarget', 'http://domain.tld', 'root') // handle all requests that starts with /mytarget
router.addRoute('/mytarget/register', 'http://domain.tld/register', 'register', 'POST') // expect the register POST

Method matches

You can see above how to handle different methods, by default all methods are handle by a route.

Complex examples

In some cases, especially when headers and other matchers are required, the simple interface might not be enough, in that case it is possible to use

  • the raw route config
  • use the route builder

If you don't plan to use any automatic route generation from JSON files you can skip the raw config section and continue with the builder.

The raw config

The structure of routes looks the following and is best explained with an example.

var route = {
  id: 'myid',
  matcher: {
    path: {
      match: 'regex|path', // simply add a regex as string '^/abc'
      type: 'POST|STRICT',
    },
    method: 'GET|POST|DELETE|...',
    headers: [{
      name: 'HTTP_X_REQUESTED_WITH', // header name
      value: 'xmlhttprequest', // header value
      type: 'STRICT' // currently only STRICT supported
    }]
  }
}

router.addComplexRoute(route)

There can be as many header matchers as required, but only either STRICT path or REGEX path match, same applies for method.

Route Builder

The easier way to build routes is the usage of the builder interface.

router.newRoute()
  .matchPath('/mytarget/register')
  .matchMethod('POST')
  .toEndpoint('http://domain.tld/register')
  .save()
  
router.newRoute()
  .matchPath('/mytarget/cart')
  .matchHeader('HTTP_X_REQUESTED_WITH', 'xmlhttprequest')
  .toEndpoint('http://domain.tld/register')
  .save()
  
router.newRoute()
  .matchRegexPath('^/mytarget')
  .toEndpoint('http://domain.tld')
  .save()

Filters / Middleware

Filters act like middleware but are specified and added to each route separately. They can be used to modify the request or response.

The following filters are built-in:

  • cookie - used to map a cookie to a header (request) and header to cookie (response)
  • requestHeader - adds a header to a request
  • responseHeader - adds a header to a response

Filters are autoloaded by name from defined directories, this can be configured like

router.registerFilterDirectory()
Usage of custom filters

There are two ways to achieve it

  • the filter is autoloaded from the defined include directories
  • a generator is passed instead of a name
Autoload
router.registerFilterDirectory(__dirname + '/filters')
router.newRoute('customFilter')
    .matchPath('/')
    .withFilter('customFilter', 'value')
    .toEndpoint(`http://domain.tld`)
    .save()

The custom-filter looks like, it doesn't matter if the new module export or the "old" is being used.

export default function (filterValue) {
    return function *(next) {
        this.request.headers['custom-filter'] = filterValue

        yield next
    }
}
Direct injecting filter
router.newRoute('customFilter')
    .matchPath('/')
    .withFilter(function *(next) {
        this.request.headers['custom-filter'] = 'value'
        yield next
    })
    .toEndpoint(`http://domain.tld`)
    .save()
With route builder
router.newRoute()
  .matchPath('/mytarget')
  .toEndpoint('http://domain.tld')
  .withFilter('requestHeader', 'name', 'value')
  .withFilter('responseHeader', 'name', 'value')
  .save()

Importers

To make it easier to import huge amounts of routes importers are available.

  • JSON => reading raw routes from a JSON file
  • eskip => Zalando Skipper compatible file reader
  • REST => reading raw routes from a REST endpoint, constructor additionally accepts a transform method to extract the raw routes

All importers use the same interface, pass the router in the constructor and call read with the corresponding url/path to the source, the second param is a callback and optional.

const importer = new Importer(router)

importer.read('path/url')

With callback

const importer = new Importer(router)

importer.read('path/url', function (err) {
    if (!err) console.log('import successful')
})

Rest with transform

// routes are wrapped like {routes: [{...}, {...}]}
const importer = new Importer(router, data => data.routes)

importer.read('path/url', function (err) {
    if (!err) console.log('import successful')
})