Simple HTTP Router

2.0.6 · active · verified Wed Apr 22

router-http is a lightweight (1.3 kB min+gzipped) and performant HTTP router for Node.js, currently at stable version 2.0.6. It aims to provide an Express-like middleware API while offering significantly better and more predictable performance than Express's regex-based router. Unlike Express, router-http utilizes a trie-based routing algorithm, specifically find-my-way, which guarantees near O(1) lookup time regardless of the number of registered routes. This makes it particularly suitable for applications with a large number of routes where consistent performance is critical. The package is actively maintained with frequent dependency updates and recent major version releases, supporting Node.js version 18 and above.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize router-http, define a final error/404 handler, add global middleware, declare various HTTP method routes with dynamic parameters, and start a basic Node.js HTTP server.

const http = require('http')
const createRouter = require('router-http')

const finalHandler = (error, req, res) => {
  if (error) {
    res.statusCode = error.statusCode || 500
    res.end(error.message)
  } else {
    res.statusCode = 404
    res.end('Not Found')
  }
}

const router = createRouter(finalHandler, { caseSensitive: false, ignoreTrailingSlash: true })

// Global middleware (runs on every request)
router.use((req, res, next) => {
  req.timestamp = Date.now()
  next()
})

router
  .get('/', (req, res) => res.end(`Hello World at ${req.timestamp}`))
  .post('/users', (req, res) => res.end('User created'))
  .put('/users/:id', (req, res) => res.end(`User ${req.params.id} updated`))
  .delete('/users/:id', (req, res) => res.end(`User ${req.params.id} deleted`))
  .all('/ping', (req, res) => res.end('pong'))

const server = http.createServer((req, res) => {
  router(req, res)
})

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000')
  console.log('Try visiting / or /users/123, or POST to /users')
})

view raw JSON →