Unlike Express and many other frameworks, Koa does not include a router.
Without a router, routing in Koa can be done by using this.request.path and yield next.
To check if the request matches a specific path:

  1. app.use(function* (next) {
  2. if (this.request.path === '/') {
  3. }
  4. })

To skip this middleware:

  1. app.use(function* (next) {
  2. if (skip) return yield next;
  3. })

This is very similar to Express’ next() call.

Combining this together,
you can route paths like this:

  1. app.use(function* (next) {
  2. // skip the rest of the code if the route does not match
  3. if (this.request.path !== '/') return yield next;
  4. this.response.body = 'we are at home!';
  5. })

By returning early,
we don’t need to bother having any nested if and else statements.
Note that we’re checking whether the path does not match,
then early returning.

Of course, you can write this the long way:

  1. app.use(function* (next) {
  2. if (this.request.path === '/') {
  3. this.response.body = 'hello!';
  4. } else {
  5. yield next;
  6. }
  7. })

Exercise

Create an app that returns the following responses from the following routes:

  • / - hello world
  • /404 - page not found
  • /500 - internal server error.

In a real app, having each route as its own middleware is more ideal
as it allows for easier refactoring.

Learn More

There are more properties you’re probably interested in when routing:

  • this.request.method
  • this.request.query
  • this.request.host