router-middleware

raw JSON →
6.1.6 verified Sat Apr 25 auth: no javascript

An Express-style router for Node.js with full TypeScript safety, including inferred route params from path strings (e.g., '/user/:id' gives req.params.id: string) and typed request/response bodies via generic parameters. Current stable version is 6.1.6. Key differentiators: no view engine, no global state, dual ESM/CJS exports, built-in error handling, and safe defaults (1 MB JSON limit, strict content-type checks). Released actively with regular updates; ships its own TypeScript types.

error TypeError: app is not a function
cause Incorrect import: using require('router-middleware') without .default in CJS
fix
Change to const app = require('router-middleware').default;
error Type '{}' is not assignable to type 'string'
cause Using res.send() with an object instead of res.json()
fix
Replace res.send(obj) with res.json(obj)
error Cannot find name 'app'.
cause Missing app.jsonParser() call or forgot to call createApp()
fix
Ensure const app = createApp(); is called and app.use(app.jsonParser()); is added
error Property 'params' does not exist on type 'Request'
cause Route handler not using generic parameter for path, so params is not typed
fix
Add generic type like app.get<'/path/:id'>('/path/:id', handler) to infer params
breaking Default export is ESM-only; CJS require must use .default
fix Use `const app = require('router-middleware').default;` instead of `const app = require('router-middleware');`
breaking Changed from `req.param` to `req.params` for route parameters
fix Replace `req.param('id')` with `req.params.id`
gotcha JSON body parser is not automatic; must be explicitly added with app.use(app.jsonParser())
fix Add `app.use(app.jsonParser());` before routes that expect JSON body
gotcha res.send() does NOT accept objects; use res.json() for objects
fix Use `res.json({...})` instead of `res.send({...})`
deprecated app.useError() has been renamed to app.onError() in latest v7 beta
fix Migrate to `app.onError(handler)` when upgrading to v7
npm install router-middleware
yarn add router-middleware
pnpm add router-middleware

Creates a typed HTTP server with route param inference and typed request/response bodies.

import http from 'node:http';
import createApp from 'router-middleware';

const app = createApp();
const server = http.createServer(app);

app.use(app.jsonParser());

app.get<'/user/:id'>('/user/:id', (req, res) => {
  res.json({ id: req.params.id });
});

app.post<'/user/:id/email', { email: string }, { ok: true; id: string; email: string }>(
  '/user/:id/email',
  (req, res) => {
    res.status(201).json({
      ok: true,
      id: req.params.id,
      email: req.body.email,
    });
  }
);

app.get<'/health'>('/health', (_req, res) => {
  res.status(200).send('OK');
});

app.useError((err, _req, res, _next) => {
  res.status(err?.statusCode ?? 500).json({ error: err?.message ?? 'error' });
});

server.listen(5150);