{"id":28549939,"url":"https://github.com/eggjs/router","last_synced_at":"2025-07-05T06:31:21.166Z","repository":{"id":48793281,"uuid":"168078345","full_name":"eggjs/router","owner":"eggjs","description":"router for eggjs, fork from koa-router with some additional features","archived":false,"fork":false,"pushed_at":"2025-03-27T12:08:00.000Z","size":547,"stargazers_count":50,"open_issues_count":2,"forks_count":7,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-06-09T15:55:31.127Z","etag":null,"topics":["egg","router"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eggjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-01-29T02:55:18.000Z","updated_at":"2025-05-22T03:47:45.000Z","dependencies_parsed_at":"2024-12-21T18:24:03.065Z","dependency_job_id":"caf9979b-d8b9-48aa-807c-c5271a4aad5a","html_url":"https://github.com/eggjs/router","commit_stats":{"total_commits":369,"total_committers":62,"mean_commits":5.951612903225806,"dds":"0.44986449864498645","last_synced_commit":"ffe08b9f31ce32b3c28b00029c212f94a4954118"},"previous_names":["eggjs/router"],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/eggjs/router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Frouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Frouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Frouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Frouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eggjs","download_url":"https://codeload.github.com/eggjs/router/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Frouter/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260026411,"owners_count":22947776,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["egg","router"],"created_at":"2025-06-10T02:36:13.381Z","updated_at":"2025-07-05T06:31:21.160Z","avatar_url":"https://github.com/eggjs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @eggjs/router\n\n[![NPM version](https://img.shields.io/npm/v/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router)\n[![NPM download](https://img.shields.io/npm/dm/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router)\n[![Node.js CI](https://github.com/eggjs/router/actions/workflows/nodejs.yml/badge.svg?branch=master)](https://github.com/eggjs/router/actions/workflows/nodejs.yml)\n[![Test coverage](https://img.shields.io/codecov/c/github/eggjs/router.svg?style=flat-square)](https://codecov.io/gh/eggjs/router)\n[![Known Vulnerabilities](https://snyk.io/test/npm/@eggjs/router/badge.svg?style=flat-square)](https://snyk.io/test/npm/@eggjs/router)\n[![Node.js Version](https://img.shields.io/node/v/@eggjs/router.svg?style=flat)](https://nodejs.org/en/download/)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/eggjs/router)\n\nRouter core component for [Egg.js](https://github.com/eggjs).\n\n\u003e **This repository is a fork of [koa-router](https://github.com/alexmingoia/koa-router).** with some additional features.\n\u003e And thanks for the great work of @alexmingoia and the original team.\n\n## API Reference\n\n- [@eggjs/router](#eggjsrouter)\n  - [API Reference](#api-reference)\n    - [Router ⏏](#router-)\n      - [new Router(\\[opts\\])](#new-routeropts)\n      - [router.get|put|post|patch|delete|del ⇒ Router](#routergetputpostpatchdeletedel--router)\n      - [Named routes](#named-routes)\n      - [Multiple middleware](#multiple-middleware)\n    - [Nested routers](#nested-routers)\n      - [Router prefixes](#router-prefixes)\n      - [URL parameters](#url-parameters)\n      - [router.routes ⇒ function](#routerroutes--function)\n      - [router.use(\\[path\\], middleware) ⇒ Router](#routerusepath-middleware--router)\n      - [router.prefix(prefix) ⇒ Router](#routerprefixprefix--router)\n      - [router.allowedMethods(\\[options\\]) ⇒ function](#routerallowedmethodsoptions--function)\n      - [router.redirect(source, destination, \\[code\\]) ⇒ Router](#routerredirectsource-destination-code--router)\n      - [router.route(name) ⇒ Layer | false](#routerroutename--layer--false)\n      - [router.url(name, params, \\[options\\]) ⇒ String | Error](#routerurlname-params-options--string--error)\n      - [router.param(param, middleware) ⇒ Router](#routerparamparam-middleware--router)\n      - [Router.url(path, params \\[, options\\]) ⇒ String](#routerurlpath-params--options--string)\n  - [Tests](#tests)\n  - [Breaking changes on v3](#breaking-changes-on-v3)\n  - [License](#license)\n  - [Contributors](#contributors)\n\n\u003ca name=\"exp_module_egg-router--Router\"\u003e\u003c/a\u003e\n\n### Router ⏏\n\n**Kind**: Exported class\n\u003ca name=\"new_module_egg-router--Router_new\"\u003e\u003c/a\u003e\n\n#### new Router([opts])\n\nCreate a new router.\n\n| Param | Type | Description |\n| ---   | ---   | --- |\n| [opts] | \u003ccode\u003eObject\u003c/code\u003e |  |\n| [opts.prefix] | \u003ccode\u003eString\u003c/code\u003e | prefix router paths |\n\n**Example**\nBasic usage:\n\n```ts\nimport Koa from '@eggjs/koa';\nimport Router from '@eggjs/router';\n\nconst app = new Koa();\nconst router = new Router();\n\nrouter.get('/', async (ctx, next) =\u003e {\n  // ctx.router available\n});\n\napp\n  .use(router.routes())\n  .use(router.allowedMethods());\n```\n\n\u003ca name=\"module_egg-router--Router+get|put|post|patch|delete|del\"\u003e\u003c/a\u003e\n\n#### router.get|put|post|patch|delete|del ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n\nCreate `router.verb()` methods, where *verb* is one of the HTTP verbs such\nas `router.get()` or `router.post()`.\n\nMatch URL patterns to callback functions or controller actions using `router.verb()`,\nwhere **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`.\n\nAdditionaly, `router.all()` can be used to match against all methods.\n\n```ts\nrouter\n  .get('/', (ctx, next) =\u003e {\n    ctx.body = 'Hello World!';\n  })\n  .post('/users', (ctx, next) =\u003e {\n    // ...\n  })\n  .put('/users/:id', (ctx, next) =\u003e {\n    // ...\n  })\n  .del('/users/:id', (ctx, next) =\u003e {\n    // ...\n  })\n  .all('/users/:id', (ctx, next) =\u003e {\n    // ...\n  });\n```\n\nWhen a route is matched, its path is available at `ctx.routePath` and if named,\nthe name is available at `ctx.routeName`\n\nRoute paths will be translated to regular expressions using\n[path-to-regexp](https://github.com/pillarjs/path-to-regexp).\n\nQuery strings will not be considered when matching requests.\n\n#### Named routes\n\nRoutes can optionally have names. This allows generation of URLs and easy\nrenaming of URLs during development.\n\n```ts\nrouter.get('user', '/users/:id', (ctx, next) =\u003e {\n // ...\n});\n\nrouter.url('user', 3);\n// =\u003e \"/users/3\"\n```\n\n#### Multiple middleware\n\nMultiple middleware may be given:\n\n```ts\nrouter.get(\n  '/users/:id',\n  (ctx, next) =\u003e {\n    return User.findOne(ctx.params.id).then(function(user) {\n      ctx.user = user;\n      next();\n    });\n  },\n  ctx =\u003e {\n    console.log(ctx.user);\n    // =\u003e { id: 17, name: \"Alex\" }\n  }\n);\n```\n\n### Nested routers\n\nNesting routers is supported:\n\n```ts\nconst forums = new Router();\nconst posts = new Router();\n\nposts.get('/', (ctx, next) =\u003e {...});\nposts.get('/:pid', (ctx, next) =\u003e {...});\nforums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());\n\n// responds to \"/forums/123/posts\" and \"/forums/123/posts/123\"\napp.use(forums.routes());\n```\n\n#### Router prefixes\n\nRoute paths can be prefixed at the router level:\n\n```ts\nconst router = new Router({\n  prefix: '/users'\n});\n\nrouter.get('/', ...); // responds to \"/users\"\nrouter.get('/:id', ...); // responds to \"/users/:id\"\n```\n\n#### URL parameters\n\nNamed route parameters are captured and added to `ctx.params`.\n\n```ts\nrouter.get('/:category/:title', (ctx, next) =\u003e {\n  console.log(ctx.params);\n  // =\u003e { category: 'programming', title: 'how-to-node' }\n});\n```\n\nThe [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module is\nused to convert paths to regular expressions.\n\n**Kind**: instance property of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type | Description |\n| ---   | ---  | --- |\n| path | \u003ccode\u003eString\u003c/code\u003e |  |\n| [middleware] | \u003ccode\u003efunction\u003c/code\u003e | route middleware(s) |\n| callback | \u003ccode\u003efunction\u003c/code\u003e | route callback |\n\n\u003ca name=\"module_egg-router--Router+routes\"\u003e\u003c/a\u003e\n\n#### router.routes ⇒ \u003ccode\u003efunction\u003c/code\u003e\nReturns router middleware which dispatches a route matching the request.\n\n**Kind**: instance property of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\u003ca name=\"module_egg-router--Router+use\"\u003e\u003c/a\u003e\n\n#### router.use([path], middleware) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n\nUse given middleware.\n\nMiddleware run in the order they are defined by `.use()`. They are invoked\nsequentially, requests start at the first middleware and work their way\n\"down\" the middleware stack.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type |\n| --- | --- |\n| [path] | \u003ccode\u003eString\u003c/code\u003e |\n| middleware | \u003ccode\u003efunction\u003c/code\u003e |\n| [...] | \u003ccode\u003efunction\u003c/code\u003e |\n\n**Example**\n\n```ts\n// session middleware will run before authorize\nrouter\n  .use(session())\n  .use(authorize());\n\n// use middleware only with given path\nrouter.use('/users', userAuth());\n\n// or with an array of paths\nrouter.use(['/users', '/admin'], userAuth());\n\napp.use(router.routes());\n```\n\n\u003ca name=\"module_egg-router--Router+prefix\"\u003e\u003c/a\u003e\n\n#### router.prefix(prefix) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n\nSet the path prefix for a Router instance that was already initialized.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type |\n| --- | --- |\n| prefix | \u003ccode\u003eString\u003c/code\u003e |\n\n**Example**\n\n```ts\nrouter.prefix('/things/:thing_id')\n```\n\n\u003ca name=\"module_egg-router--Router+allowedMethods\"\u003e\u003c/a\u003e\n\n#### router.allowedMethods([options]) ⇒ \u003ccode\u003efunction\u003c/code\u003e\n\nReturns separate middleware for responding to `OPTIONS` requests with\nan `Allow` header containing the allowed methods, as well as responding\nwith `405 Method Not Allowed` and `501 Not Implemented` as appropriate.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type | Description |\n| --- | --- | --- |\n| [options] | \u003ccode\u003eObject\u003c/code\u003e |  |\n| [options.throw] | \u003ccode\u003eBoolean\u003c/code\u003e | throw error instead of setting status and header |\n| [options.notImplemented] | \u003ccode\u003efunction\u003c/code\u003e | throw the returned value in place of the default NotImplemented error |\n| [options.methodNotAllowed] | \u003ccode\u003efunction\u003c/code\u003e | throw the returned value in place of the default MethodNotAllowed error |\n\n**Example**\n\n```ts\nimport Koa from '@eggjs/koa';\nimport Router from '@eggjs/router';\n\nconst app = new Koa();\nconst router = new Router();\n\napp.use(router.routes());\napp.use(router.allowedMethods());\n```\n\n**Example with [Boom](https://github.com/hapijs/boom)**\n\n```ts\nimport Koa from '@eggjs/koa';\nimport Router from '@eggjs/router';\nimport Boom from 'boom';\n\nconst app = new Koa();\nconst router = new Router();\n\napp.use(router.routes());\napp.use(router.allowedMethods({\n  throw: true,\n  notImplemented: () =\u003e new Boom.notImplemented(),\n  methodNotAllowed: () =\u003e new Boom.methodNotAllowed()\n}));\n```\n\n\u003ca name=\"module_egg-router--Router+redirect\"\u003e\u003c/a\u003e\n\n#### router.redirect(source, destination, [code]) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n\nRedirect `source` to `destination` URL with optional 30x status `code`.\n\nBoth `source` and `destination` can be route names.\n\n```javascript\nrouter.redirect('/login', 'sign-in');\n```\n\nThis is equivalent to:\n\n```ts\nrouter.all('/login', ctx =\u003e {\n  ctx.redirect('/sign-in');\n  ctx.status = 301;\n});\n```\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type | Description |\n| --- | --- | --- |\n| source | \u003ccode\u003eString\u003c/code\u003e | URL or route name. |\n| destination | \u003ccode\u003eString\u003c/code\u003e | URL or route name. |\n| [code] | \u003ccode\u003eNumber\u003c/code\u003e | HTTP status code (default: 301). |\n\n\u003ca name=\"module_egg-router--Router+route\"\u003e\u003c/a\u003e\n\n#### router.route(name) ⇒ \u003ccode\u003eLayer\u003c/code\u003e \u0026#124; \u003ccode\u003efalse\u003c/code\u003e\n\nLookup route with given `name`.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type |\n| --- | --- |\n| name | \u003ccode\u003eString\u003c/code\u003e |\n\n\u003ca name=\"module_egg-router--Router+url\"\u003e\u003c/a\u003e\n\n#### router.url(name, params, [options]) ⇒ \u003ccode\u003eString\u003c/code\u003e \u0026#124; \u003ccode\u003eError\u003c/code\u003e\n\nGenerate URL for route. Takes a route name and map of named `params`.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type | Description |\n| --- | --- | --- |\n| name | \u003ccode\u003eString\u003c/code\u003e | route name |\n| params | \u003ccode\u003eObject\u003c/code\u003e | url parameters |\n| [options] | \u003ccode\u003eObject\u003c/code\u003e | options parameter |\n| [options.query] | \u003ccode\u003eObject\u003c/code\u003e \u0026#124; \u003ccode\u003eString\u003c/code\u003e | query options |\n\n**Example**\n\n```ts\nrouter.get('user', '/users/:id', (ctx, next) =\u003e {\n  // ...\n});\n\nrouter.url('user', 3);\n// =\u003e \"/users/3\"\n\nrouter.url('user', { id: 3 });\n// =\u003e \"/users/3\"\n\nrouter.use((ctx, next) =\u003e {\n  // redirect to named route\n  ctx.redirect(ctx.router.url('sign-in'));\n})\n\nrouter.url('user', { id: 3 }, { query: { limit: 1 } });\n// =\u003e \"/users/3?limit=1\"\n\nrouter.url('user', { id: 3 }, { query: \"limit=1\" });\n// =\u003e \"/users/3?limit=1\"\n```\n\n\u003ca name=\"module_egg-router--Router+param\"\u003e\u003c/a\u003e\n\n#### router.param(param, middleware) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n\nRun middleware for named route parameters. Useful for auto-loading or\nvalidation.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type |\n| --- | --- |\n| param | \u003ccode\u003eString\u003c/code\u003e |\n| middleware | \u003ccode\u003efunction\u003c/code\u003e |\n\n**Example**\n\n```ts\nrouter\n  .param('user', (id, ctx, next) =\u003e {\n    ctx.user = users[id];\n    if (!ctx.user) return ctx.status = 404;\n    return next();\n  })\n  .get('/users/:user', ctx =\u003e {\n    ctx.body = ctx.user;\n  })\n  .get('/users/:user/friends', ctx =\u003e {\n    return ctx.user.getFriends().then(function(friends) {\n      ctx.body = friends;\n    });\n  })\n  // /users/3 =\u003e {\"id\": 3, \"name\": \"Alex\"}\n  // /users/3/friends =\u003e [{\"id\": 4, \"name\": \"TJ\"}]\n```\n\n\u003ca name=\"module_egg-router--Router.url\"\u003e\u003c/a\u003e\n\n#### Router.url(path, params [, options]) ⇒ \u003ccode\u003eString\u003c/code\u003e\n\nGenerate URL from url pattern and given `params`.\n\n**Kind**: static method of \u003ccode\u003e[Router](#exp_module_egg-router--Router)\u003c/code\u003e\n\n| Param | Type | Description |\n| --- | --- | --- |\n| path | \u003ccode\u003eString\u003c/code\u003e | url pattern |\n| params | \u003ccode\u003eObject\u003c/code\u003e | url parameters |\n| [options] | \u003ccode\u003eObject\u003c/code\u003e | options parameter |\n| [options.query] | \u003ccode\u003eObject\u003c/code\u003e \u0026#124; \u003ccode\u003eString\u003c/code\u003e | query options |\n\n**Example**\n\n```ts\nconst url = Router.url('/users/:id', {id: 1});\n// =\u003e \"/users/1\"\n\nconst url = Router.url('/users/:id', {id: 1}, {query: { active: true }});\n// =\u003e \"/users/1?active=true\"\n```\n\n## Tests\n\nRun tests using `npm test`.\n\n## Breaking changes on v3\n\n- Drop generator function support\n- Drop Node.js \u003c 18.19.0 support\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=eggjs/router)](https://github.com/eggjs/router/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feggjs%2Frouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feggjs%2Frouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feggjs%2Frouter/lists"}