Installations
npm install router
Developer Guide
Typescript
No
Module System
N/A
Min. Node Version
>= 0.8
Node Version
18.13.0
NPM Version
8.19.3
Score
98.5
Supply Chain
99.1
Quality
82.3
Maintenance
50
Vulnerability
100
License
Releases
Contributors
Languages
JavaScript (100%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
pillarjs
Download Statistics
Total Downloads
148,186,056
Last Day
333,121
Last Week
1,753,409
Last Month
6,754,111
Last Year
41,666,217
GitHub Statistics
MIT License
417 Stars
394 Commits
107 Forks
18 Watchers
10 Branches
35 Contributors
Updated on Mar 05, 2025
Bundle Size
14.99 kB
Minified
5.59 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.3.8
Package Id
router@1.3.8
Unpacked Size
41.58 kB
Size
12.90 kB
File Count
8
NPM Version
8.19.3
Node Version
18.13.0
Published on
Feb 24, 2023
Total Downloads
Cumulative downloads
Total Downloads
148,186,056
Last Day
14.1%
333,121
Compared to previous day
Last Week
9%
1,753,409
Compared to previous week
Last Month
37.5%
6,754,111
Compared to previous month
Last Year
38.1%
41,666,217
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
router
Simple middleware-style router
Installation
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
1$ npm install router
API
1var finalhandler = require('finalhandler') 2var http = require('http') 3var Router = require('router') 4 5var router = Router() 6router.get('/', function (req, res) { 7 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 8 res.end('Hello World!') 9}) 10 11var server = http.createServer(function(req, res) { 12 router(req, res, finalhandler(req, res)) 13}) 14 15server.listen(3000)
This module is currently an extracted version from the Express project,
but with the main change being it can be used with a plain http.createServer
object or other web frameworks by removing Express-specific API calls.
Router(options)
Options
strict
- Whenfalse
trailing slashes are optional (default:false
)caseSensitive
- Whentrue
the routing will be case sensitive. (default:false
)mergeParams
- Whentrue
anyreq.params
passed to the router will be merged into the router'sreq.params
. (default:false
) (example)
Returns a function with the signature router(req, res, callback)
where
callback([err])
must be provided to handle errors and fall-through from
not handling requests.
router.use([path], ...middleware)
Use the given middleware function for all http methods on the
given path
, defaulting to the root path.
router
does not automatically see use
as a handler. As such, it will not
consider it one for handling OPTIONS
requests.
- Note: If a
path
is specified, thatpath
is stripped from the start ofreq.url
.
1router.use(function (req, res, next) { 2 // do your things 3 4 // continue to the next middleware 5 // the request will stall if this is not called 6 next() 7 8 // note: you should NOT call `next` if you have begun writing to the response 9})
Middleware can themselves use next('router')
at any time to
exit the current router instance completely, invoking the top-level callback.
router[method](path, ...[middleware], handler)
The http methods provide
the routing functionality in router
.
Method middleware and handlers follow usual middleware behavior, except they will only be called when the method and path match the request.
1// handle a `GET` request 2router.get('/', function (req, res) { 3 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 4 res.end('Hello World!') 5})
Middleware given before the handler have one additional trick,
they may invoke next('route')
. Calling next('route')
bypasses the remaining
middleware and the handler mounted for this route, passing the request to the
next route suitable for handling this request.
Route handlers and middleware can themselves use next('router')
at any time
to exit the current router instance completely, invoking the top-level callback.
router.param(name, param_middleware)
Maps the specified path parameter name
to a specialized param-capturing middleware.
This function positions the middleware in the same stack as .use
.
Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. For example a :user_id parameter could automatically load a user's information from the database without any additional code:
1router.param('user_id', function (req, res, next, id) { 2 User.find(id, function (err, user) { 3 if (err) { 4 return next(err) 5 } else if (!user) { 6 return next(new Error('failed to load user')) 7 } 8 req.user = user 9 10 // continue processing the request 11 next() 12 }) 13})
router.route(path)
Creates an instance of a single Route
for the given path
.
(See Router.Route
below)
Routes can be used to handle http methods
with their own, optional middleware.
Using router.route(path)
is a recommended approach to avoiding duplicate
route naming and thus typo errors.
1var api = router.route('/api/')
Router.Route(path)
Represents a single route as an instance that can be used to handle http
methods
with it's own, optional middleware.
route[method](handler)
These are functions which you can directly call on a route to register a new
handler
for the method
on the route.
1// handle a `GET` request 2var status = router.route('/status') 3 4status.get(function (req, res) { 5 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 6 res.end('All Systems Green!') 7})
route.all(handler)
Adds a handler for all HTTP methods to this route.
The handler can behave like middleware and call next
to continue processing
rather than responding.
1router.route('/') 2 .all(function (req, res, next) { 3 next() 4 }) 5 .all(check_something) 6 .get(function (req, res) { 7 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 8 res.end('Hello World!') 9 })
Middleware
Middleware (and method handlers) are functions that follow specific function
parameters and have defined behavior when used with router
. The most common
format is with three parameters - "req", "res" and "next".
req
- This is a HTTP incoming message instance.res
- This is a HTTP server response instance.next
- Calling this function that tellsrouter
to proceed to the next matching middleware or method handler. It accepts an error as the first argument.
Middleware and method handlers can also be defined with four arguments. When
the function has four parameters defined, the first argument is an error and
subsequent arguments remain, becoming - "err", "req", "res", "next". These
functions are "error handling middleware", and can be used for handling
errors that occurred in previous handlers (E.g. from calling next(err)
).
This is most used when you want to define arbitrary rendering of errors.
1router.get('/error_route', function (req, res, next) { 2 return next(new Error('Bad Request')) 3}) 4 5router.use(function (err, req, res, next) { 6 res.end(err.message) //=> "Bad Request" 7})
Error handling middleware will only be invoked when an error was given. As long as the error is in the pipeline, normal middleware and handlers will be bypassed - only error handling middleware will be invoked with an error.
Examples
1// import our modules 2var http = require('http') 3var Router = require('router') 4var finalhandler = require('finalhandler') 5var compression = require('compression') 6var bodyParser = require('body-parser') 7 8// store our message to display 9var message = "Hello World!" 10 11// initialize the router & server and add a final callback. 12var router = Router() 13var server = http.createServer(function onRequest(req, res) { 14 router(req, res, finalhandler(req, res)) 15}) 16 17// use some middleware and compress all outgoing responses 18router.use(compression()) 19 20// handle `GET` requests to `/message` 21router.get('/message', function (req, res) { 22 res.statusCode = 200 23 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 24 res.end(message + '\n') 25}) 26 27// create and mount a new router for our API 28var api = Router() 29router.use('/api/', api) 30 31// add a body parsing middleware to our API 32api.use(bodyParser.json()) 33 34// handle `PATCH` requests to `/api/set-message` 35api.patch('/set-message', function (req, res) { 36 if (req.body.value) { 37 message = req.body.value 38 39 res.statusCode = 200 40 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 41 res.end(message + '\n') 42 } else { 43 res.statusCode = 400 44 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 45 res.end('Invalid API Syntax\n') 46 } 47}) 48 49// make our http server listen to connections 50server.listen(8080)
You can get the message by running this command in your terminal,
or navigating to 127.0.0.1:8080
in a web browser.
1curl http://127.0.0.1:8080
You can set the message by sending it a PATCH
request via this command:
1curl http://127.0.0.1:8080/api/set-message -X PATCH -H "Content-Type: application/json" -d '{"value":"Cats!"}'
Example using mergeParams
1var http = require('http') 2var Router = require('router') 3var finalhandler = require('finalhandler') 4 5// this example is about the mergeParams option 6var opts = { mergeParams: true } 7 8// make a router with out special options 9var router = Router(opts) 10var server = http.createServer(function onRequest(req, res) { 11 12 // set something to be passed into the router 13 req.params = { type: 'kitten' } 14 15 router(req, res, finalhandler(req, res)) 16}) 17 18router.get('/', function (req, res) { 19 res.statusCode = 200 20 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 21 22 // with respond with the the params that were passed in 23 res.end(req.params.type + '\n') 24}) 25 26// make another router with our options 27var handler = Router(opts) 28 29// mount our new router to a route that accepts a param 30router.use('/:path', handler) 31 32handler.get('/', function (req, res) { 33 res.statusCode = 200 34 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 35 36 // will respond with the param of the router's parent route 37 res.end(req.params.path + '\n') 38}) 39 40// make our http server listen to connections 41server.listen(8080)
Now you can get the type, or what path you are requesting:
1curl http://127.0.0.1:8080 2> kitten 3curl http://127.0.0.1:8080/such_path 4> such_path
Example of advanced .route()
usage
This example shows how to implement routes where there is a custom
handler to execute when the path matched, but no methods matched.
Without any special handling, this would be treated as just a
generic non-match by router
(which typically results in a 404),
but with a custom handler, a 405 Method Not Allowed
can be sent.
1var http = require('http') 2var finalhandler = require('finalhandler') 3var Router = require('router') 4 5// create the router and server 6var router = new Router() 7var server = http.createServer(function onRequest(req, res) { 8 router(req, res, finalhandler(req, res)) 9}) 10 11// register a route and add all methods 12router.route('/pet/:id') 13 .get(function (req, res) { 14 // this is GET /pet/:id 15 res.setHeader('Content-Type', 'application/json') 16 res.end(JSON.stringify({ name: 'tobi' })) 17 }) 18 .delete(function (req, res) { 19 // this is DELETE /pet/:id 20 res.end() 21 }) 22 .all(function (req, res) { 23 // this is called for all other methods not 24 // defined above for /pet/:id 25 res.statusCode = 405 26 res.end() 27 }) 28 29// make our http server listen to connections 30server.listen(8080)
License

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
project has 17 contributing companies or organizations
Details
- Info: crypto-utils contributor org/company found, Netflix contributor org/company found, expressjs contributor org/company found, stream-utils contributor org/company found, restify contributor org/company found, pillarjs contributor org/company found, pkgjs contributor org/company found, netflix contributor org/company found, repo-utils contributor org/company found, ExpressGateway contributor org/company found, jshttp contributor org/company found, migratejs contributor org/company found, nodejs contributor org/company found, Node-Ops contributor org/company found, MusicMapIo contributor org/company found, sprengnetter austria gmbh contributor org/company found, mysqljs contributor org/company found,
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
11 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/pillarjs/.github/SECURITY.md:1
- Info: Found linked content: github.com/pillarjs/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/pillarjs/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/pillarjs/.github/SECURITY.md:1
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/ci.yml:52
- Warn: jobLevel 'checks' permission set to 'write': .github/workflows/ci.yml:53
- Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:13
- Info: topLevel permissions set to 'read-all': .github/workflows/scorecard.yml:19
Reason
0 existing vulnerabilities detected
Reason
23 out of 25 merged PRs checked by a CI test -- score normalized to 9
Reason
Found 23/26 approved changesets -- score normalized to 8
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:42: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:55: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:62: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:72: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/router/ci.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:34
- Info: 3 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 2 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
no update tool detected
Details
- Warn: no dependency update tool configurations found
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 29 are checked with a SAST tool
Score
6.5
/10
Last Scanned on 2025-03-10T21:29:53Z
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to router
Router
A simple router that uses regular expressions to match URLs.
vue-router
> - This is the repository for Vue Router 4 (for Vue 3) > - For Vue Router 3 (for Vue 2) see [vuejs/vue-router](https://github.com/vuejs/vue-router).
@vue/cli-plugin-router
router plugin for vue-cli
react-router
Declarative routing for React