What is koa-router?
koa-router is a powerful routing middleware for Koa, a next-generation web framework for Node.js. It allows you to define routes for your web application, handle HTTP methods, and manage middleware in a clean and organized manner.
What are koa-router's main functionalities?
Basic Routing
This code demonstrates how to set up a basic route using koa-router. When a GET request is made to the root URL '/', it responds with 'Hello World!'.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/', (ctx, next) => {
ctx.body = 'Hello World!';
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Route Parameters
This code demonstrates how to use route parameters with koa-router. When a GET request is made to '/users/:id', it responds with the user ID provided in the URL.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/users/:id', (ctx, next) => {
const userId = ctx.params.id;
ctx.body = `User ID: ${userId}`;
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Middleware
This code demonstrates how to use middleware with koa-router. The logger middleware logs the HTTP method and URL of each request before passing control to the next middleware or route handler.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const logger = async (ctx, next) => {
console.log(`${ctx.method} ${ctx.url}`);
await next();
};
router.get('/', logger, (ctx, next) => {
ctx.body = 'Hello World!';
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Nested Routes
This code demonstrates how to create nested routes with koa-router. The nestedRouter handles requests to '/nested/info' and responds with 'Nested Route Info'.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const nestedRouter = new Router();
nestedRouter.get('/info', (ctx, next) => {
ctx.body = 'Nested Route Info';
});
router.use('/nested', nestedRouter.routes(), nestedRouter.allowedMethods());
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Other packages similar to koa-router
express
Express is a fast, unopinionated, minimalist web framework for Node.js. It provides robust routing capabilities similar to koa-router but is more widely used and has a larger ecosystem of middleware and plugins.
hapi
Hapi is a rich framework for building applications and services. It provides powerful configuration-based routing and extensive support for building scalable and maintainable applications. Compared to koa-router, Hapi offers more built-in features and a more opinionated structure.
restify
Restify is a framework specifically designed for building RESTful web services. It provides a similar routing mechanism to koa-router but is optimized for building APIs with a focus on performance and scalability.
Router middleware for koa
- Express-style routing using
app.get
, app.put
, app.post
, etc. - Named URL parameters and regexp captures.
- String or regular expression route matching.
- Named routes with URL generation.
- Responds to
OPTIONS
requests with allowed methods. - Support for
405 Method Not Allowed
and 501 Not Implemented
. - Multiple route middleware.
- Multiple routers.
Install
koa-router is available using npm:
npm install koa-router
Usage
Require the router and mount the middleware:
var koa = require('koa')
, router = require('koa-router')
, app = koa();
app.use(router(app));
After the router has been initialized you can register routes:
app.get('/users/:id', function *(next) {
var user = yield User.findOne(this.params.id);
this.body = user;
});
Multiple routers
You can use multiple routers and sets of routes by omitting the app
argument. For example, separate routers for two versions of an API:
var APIv1 = new Router();
var APIv2 = new Router();
APIv1.get('/sign-in', function *() {
});
APIv2.get('/sign-in', function *() {
});
app.use(mount('/v1', APIv1.middleware()));
app.use(mount('/v2', APIv2.middleware()));
Chaining
The http methods (get, post, etc) return their Router
instance,
so routes can be chained as you're used to with express:
var api = new Router();
api
.get('/foo', showFoo)
.get('/bar', showBar)
.post('/foo', createFoo);
API
Migrating from 2.x to 3.x
Resource routing was separated into the
koa-resource-router
module.
Router#verb([name, ]path, middleware[, middleware...])
Match URL patterns to callback functions or controller actions using router.verb()
,
where verb is one of the HTTP verbs such as router.get()
or router.post()
.
app.get('/', function *(next) {
this.body = 'Hello World!';
});
app.post('/users', function *(next) {
});
app.put('/users/:id', function *(next) {
});
app.del('/users/:id', function *(next) {
});
Route paths will be translated to regular expressions used to match requests.
Query strings will not be considered when matching requests.
Named routes
Routes can optionally have names. This allows generation of URLs and easy
renaming of URLs during development.
app.get('user', '/users/:id', function *(next) {
});
app.url('user', 3);
Multiple middleware
Multiple middleware may be given and are composed using
koa-compose:
app.get(
'/users/:id',
function *(next) {
this.user = yield User.findOne(this.params.id);
yield next;
},
function *(next) {
console.log(this.user);
}
);
URL parameters
Named route parameters are captured and added to ctx.params
.
Capture groups from regular expression routes are also added to
ctx.params
, which is an array.
Named parameters
app.get('/:category/:title', function *(next) {
console.log(this.params);
});
Regular expression captures
app.get(^\/([^\/]+)\/([^\/]+)\/?$, function *(next) {
console.log(this.params);
});
Regular expressions
Control route matching exactly by specifying a regular expression instead of
a path string when creating the route. For example, it might be useful to match
date formats for a blog, such as /blog/2013-09-04
:
app.get(/^\/blog\/\d{4}-\d{2}-\d{2}\/?$/i, function *(next) {
});
Multiple methods
Create routes with multiple HTTP methods using router.register()
:
app.register('/', ['get', 'post'], function *(next) {
});
Create route for all methods using router.all()
:
app.all('/', function *(next) {
});
Router#redirect(source, destination, [code])
Redirect source
to destination
URL with optional 30x status code
.
Both source
and destination
can be route names.
app.redirect('/login', 'sign-in');
This is equivalent to:
app.all('/login', function *() {
this.redirect('/sign-in');
this.status = 301;
});
Router#route(name)
Lookup route with given name
. Returns the route or false
.
Router#url(name, params)
Generate URL for route. Takes either map of named params
or series of
arguments (for regular expression routes).
Returns Error
if no route is found with given name
.
app.get('user', '/users/:id', function *(next) {
});
app.url('user', 3);
app.url('user', { id: 3 });
Tests
Tests use mocha and can be run
with npm:
npm test
MIT Licensed