{"id":13474990,"url":"https://github.com/ZijianHe/koa-router","last_synced_at":"2025-03-26T22:31:36.756Z","repository":{"id":10359616,"uuid":"12499274","full_name":"ZijianHe/koa-router","owner":"ZijianHe","description":"Router middleware for koa.","archived":false,"fork":false,"pushed_at":"2021-05-12T08:52:54.000Z","size":699,"stargazers_count":4851,"open_issues_count":82,"forks_count":406,"subscribers_count":44,"default_branch":"master","last_synced_at":"2024-10-29T15:27:29.844Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ZijianHe.png","metadata":{"files":{"readme":"README.md","changelog":"history.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-08-31T02:07:51.000Z","updated_at":"2024-10-28T14:01:52.000Z","dependencies_parsed_at":"2022-09-05T16:51:44.684Z","dependency_job_id":null,"html_url":"https://github.com/ZijianHe/koa-router","commit_stats":null,"previous_names":["alexmingoia/koa-router"],"tags_count":78,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZijianHe%2Fkoa-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZijianHe%2Fkoa-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZijianHe%2Fkoa-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZijianHe%2Fkoa-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZijianHe","download_url":"https://codeload.github.com/ZijianHe/koa-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245675614,"owners_count":20654430,"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":[],"created_at":"2024-07-31T16:01:16.526Z","updated_at":"2025-03-26T22:31:34.288Z","avatar_url":"https://github.com/ZijianHe.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# koa-router\n\n[![NPM version](https://img.shields.io/npm/v/koa-router.svg?style=flat)](https://npmjs.org/package/koa-router) [![NPM Downloads](https://img.shields.io/npm/dm/koa-router.svg?style=flat)](https://npmjs.org/package/koa-router) [![Node.js Version](https://img.shields.io/node/v/koa-router.svg?style=flat)](http://nodejs.org/download/) [![Build Status](https://img.shields.io/travis/alexmingoia/koa-router.svg?style=flat)](http://travis-ci.org/alexmingoia/koa-router) [![Gitter Chat](https://img.shields.io/badge/gitter-join%20chat-1dce73.svg?style=flat)](https://gitter.im/alexmingoia/koa-router/)\n\n\u003e Router middleware for [koa](https://github.com/koajs/koa)\n\n* Express-style routing using `app.get`, `app.put`, `app.post`, etc.\n* Named URL parameters.\n* Named routes with URL generation.\n* Responds to `OPTIONS` requests with allowed methods.\n* Support for `405 Method Not Allowed` and `501 Not Implemented`.\n* Multiple route middleware.\n* Multiple routers.\n* Nestable routers.\n* ES7 async/await support.\n\n## Migrating to 7 / Koa 2\n\n- The API has changed to match the new promise-based middleware\n  signature of koa 2. See the\n  [koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more\n  information.\n- Middleware is now always run in the order declared by `.use()` (or `.get()`,\n  etc.), which matches Express 4 API.\n\n## Installation\n\nInstall using [npm](https://www.npmjs.org/):\n\n```sh\nnpm install koa-router\n```\n\n## API Reference\n  \n* [koa-router](#module_koa-router)\n    * [Router](#exp_module_koa-router--Router) ⏏\n        * [new Router([opts])](#new_module_koa-router--Router_new)\n        * _instance_\n            * [.get|put|post|patch|delete|del](#module_koa-router--Router+get|put|post|patch|delete|del) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n            * [.routes](#module_koa-router--Router+routes) ⇒ \u003ccode\u003efunction\u003c/code\u003e\n            * [.use([path], middleware)](#module_koa-router--Router+use) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n            * [.prefix(prefix)](#module_koa-router--Router+prefix) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n            * [.allowedMethods([options])](#module_koa-router--Router+allowedMethods) ⇒ \u003ccode\u003efunction\u003c/code\u003e\n            * [.redirect(source, destination, [code])](#module_koa-router--Router+redirect) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n            * [.route(name)](#module_koa-router--Router+route) ⇒ \u003ccode\u003eLayer\u003c/code\u003e \u0026#124; \u003ccode\u003efalse\u003c/code\u003e\n            * [.url(name, params, [options])](#module_koa-router--Router+url) ⇒ \u003ccode\u003eString\u003c/code\u003e \u0026#124; \u003ccode\u003eError\u003c/code\u003e\n            * [.param(param, middleware)](#module_koa-router--Router+param) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\n        * _static_\n            * [.url(path, params)](#module_koa-router--Router.url) ⇒ \u003ccode\u003eString\u003c/code\u003e\n\n\u003ca name=\"exp_module_koa-router--Router\"\u003e\u003c/a\u003e\n\n### Router ⏏\n**Kind**: Exported class  \n\u003ca name=\"new_module_koa-router--Router_new\"\u003e\u003c/a\u003e\n\n#### new Router([opts])\nCreate a new router.\n\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```javascript\nvar Koa = require('koa');\nvar Router = require('koa-router');\n\nvar app = new Koa();\nvar router = new Router();\n\nrouter.get('/', (ctx, next) =\u003e {\n  // ctx.router available\n});\n\napp\n  .use(router.routes())\n  .use(router.allowedMethods());\n```\n\u003ca name=\"module_koa-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\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```javascript\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._matchedRoute` and if named,\nthe name is available at `ctx._matchedRouteName`\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```javascript\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```javascript\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```javascript\nvar forums = new Router();\nvar 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```javascript\nvar 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```javascript\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_koa-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_koa-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_koa-router--Router)\u003c/code\u003e  \n\u003ca name=\"module_koa-router--Router+use\"\u003e\u003c/a\u003e\n\n#### router.use([path], middleware) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\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_koa-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```javascript\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\u003ca name=\"module_koa-router--Router+prefix\"\u003e\u003c/a\u003e\n\n#### router.prefix(prefix) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\nSet the path prefix for a Router instance that was already initialized.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_koa-router--Router)\u003c/code\u003e  \n\n| Param | Type |\n| --- | --- |\n| prefix | \u003ccode\u003eString\u003c/code\u003e | \n\n**Example**  \n```javascript\nrouter.prefix('/things/:thing_id')\n```\n\u003ca name=\"module_koa-router--Router+allowedMethods\"\u003e\u003c/a\u003e\n\n#### router.allowedMethods([options]) ⇒ \u003ccode\u003efunction\u003c/code\u003e\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_koa-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```javascript\nvar Koa = require('koa');\nvar Router = require('koa-router');\n\nvar app = new Koa();\nvar 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```javascript\nvar Koa = require('koa');\nvar Router = require('koa-router');\nvar Boom = require('boom');\n\nvar app = new Koa();\nvar 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\u003ca name=\"module_koa-router--Router+redirect\"\u003e\u003c/a\u003e\n\n#### router.redirect(source, destination, [code]) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\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```javascript\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_koa-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_koa-router--Router+route\"\u003e\u003c/a\u003e\n\n#### router.route(name) ⇒ \u003ccode\u003eLayer\u003c/code\u003e \u0026#124; \u003ccode\u003efalse\u003c/code\u003e\nLookup route with given `name`.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_koa-router--Router)\u003c/code\u003e  \n\n| Param | Type |\n| --- | --- |\n| name | \u003ccode\u003eString\u003c/code\u003e | \n\n\u003ca name=\"module_koa-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\nGenerate URL for route. Takes a route name and map of named `params`.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_koa-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```javascript\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\u003ca name=\"module_koa-router--Router+param\"\u003e\u003c/a\u003e\n\n#### router.param(param, middleware) ⇒ \u003ccode\u003eRouter\u003c/code\u003e\nRun middleware for named route parameters. Useful for auto-loading or\nvalidation.\n\n**Kind**: instance method of \u003ccode\u003e[Router](#exp_module_koa-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```javascript\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\u003ca name=\"module_koa-router--Router.url\"\u003e\u003c/a\u003e\n\n#### Router.url(path, params [, options]) ⇒ \u003ccode\u003eString\u003c/code\u003e\nGenerate URL from url pattern and given `params`.\n\n**Kind**: static method of \u003ccode\u003e[Router](#exp_module_koa-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```javascript\nvar 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## Contributing\n\nPlease submit all issues and pull requests to the [alexmingoia/koa-router](http://github.com/alexmingoia/koa-router) repository!\n\n## Tests\n\nRun tests using `npm test`.\n\n## Support\n\nIf you have any problem or suggestion please open an issue [here](https://github.com/alexmingoia/koa-router/issues).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZijianHe%2Fkoa-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FZijianHe%2Fkoa-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZijianHe%2Fkoa-router/lists"}