Router

2.2.0 · active · verified Wed Apr 22

The `router` package provides a simple, middleware-style routing solution for Node.js HTTP servers. It is currently at version 2.2.0, with releases occurring periodically, often incorporating dependency updates and internal refactorings to reduce its external footprint, as seen in recent 2.x versions. This module was originally extracted from the Express project, offering a lightweight alternative that can be used directly with Node.js's native `http.createServer` or integrated into other web frameworks. Key differentiators include its minimalistic API, adherence to the familiar `(req, res, next)` middleware signature, and flexible routing capabilities through HTTP method-specific handlers (`router.get`, `router.post`, etc.) and general-purpose middleware (`router.use`). It supports asynchronous middleware, including Promises, and offers options for strictness, case sensitivity, and parameter merging.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up a Node.js HTTP server using `router` to handle GET and POST requests, demonstrates global middleware, custom `Router` options, and the critical role of `finalhandler` for comprehensive request and error management. It also illustrates `next('route')` for fine-grained control.

import http from 'node:http';
import Router from 'router';
import finalhandler from 'finalhandler';

const router = Router({
  caseSensitive: false, // paths like /hello and /Hello are treated the same
  strict: false // trailing slashes are optional
});

// Global middleware to log incoming requests
router.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Must call next to pass control to subsequent middleware/routes
});

// Handle a GET request to the root path
router.get('/', (req, res) => {
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.end('Hello from the Router!');
});

// Handle a POST request to '/data'
router.post('/data', (req, res) => {
  let body = '';
  req.on('data', chunk => { body += chunk; });
  req.on('end', () => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ received: body, status: 'ok' }));
  });
});

// Middleware demonstrating next('route') to skip subsequent handlers for the current route
router.get('/skip-example', (req, res, next) => {
  if (req.query.skip) {
    console.log('Skipping to the next route handler...');
    return next('route'); // Skip this handler and the next for this route
  }
  next();
}, (req, res) => {
  res.end('This handler will be skipped if ?skip=true is in the query.');
});

const server = http.createServer((req, res) => {
  // The router processes the request; if no route matches or an error occurs,
  // finalhandler ensures a proper HTTP response is sent.
  router(req, res, finalhandler(req, res, { onerror: console.error }));
});

server.listen(3000, () => {
  console.log('Router server listening on http://localhost:3000');
});

view raw JSON →