Server Router for Streaming HTTP

6.1.0 · active · verified Wed Apr 22

server-router is a Node.js HTTP router designed for streaming servers, leveraging a radix-trie data structure for high-performance route matching. It provides a concise API for defining routes with HTTP methods, including support for route parameters and wildcard paths. The current stable version is 6.1.0. Given its "experimental" stability rating as indicated by its documentation, its release cadence is irregular and breaking changes are possible without strict adherence to semantic versioning. It differentiates itself by focusing on server-side streaming applications and efficient routing, contrasting with client-side alternatives like nanorouter or more general-purpose routing solutions, by offering a low-level, performant foundation. It is suitable for applications where minimal overhead and direct HTTP stream handling are critical.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic HTTP server with multiple routes using GET, PUT, and combined methods, including a 404 handler and dynamic parameter extraction.

var serverRouter = require('server-router')
var http = require('http')

var router = serverRouter({ default: '/404' })

router.route('GET', '/hello', function (req, res, params) {
  res.end('hello world')
})

router.route('PUT', '/hello/:name', function (req, res, params) {
  res.end('hi there ' + params.name)
})

router.route(['GET', 'POST'], '/json', function (req, res, params) {
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ message: 'Dynamic JSON response', params }))
})

router.route('', '/404', function (req, res, params) {
  res.statusCode = 404
  res.end('404 Not Found')
})

const server = http.createServer(router.start())
const PORT = process.env.PORT ?? 3000

server.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`)
  console.log('Try visiting: http://localhost:3000/hello')
  console.log('Try visiting: http://localhost:3000/hello/Alice (e.g., via curl -X PUT)')
  console.log('Try visiting: http://localhost:3000/json')
  console.log('Try visiting: http://localhost:3000/nonexistent')
})

view raw JSON →