Routing in Koa

Koa Has No Built-In Router — Here Is What That Means

Routing in Koa

Unlike Express, Koa ships without a router. You install `@koa/router` separately and wire it in as middleware.

2 min read Level 1/5 #koa#routing#@koa/router
What you'll learn
  • Understand why Koa has no built-in routing
  • Install and identify `@koa/router`
  • Explain the method + path → handler concept

Koa is intentionally minimal. The core library gives you a request/response context and a middleware pipeline — nothing else. Routing (mapping HTTP method + path to a handler function) is deliberately left out so you can choose the router that fits your project, or skip one altogether for tiny apps.

Why No Built-In Router?

The Koa team wanted a clean separation between the HTTP server core and higher-level concerns. A router is just another piece of middleware; keeping it external means the core stays small and every part is replaceable.

The Standard Choice: @koa/router

The officially maintained package is @koa/router. Install it once alongside Koa:

npm install @koa/router

It works with ESM (the default in Node 20+):

import Router from "@koa/router";

Method + Path → Handler

Routing at its core is pattern matching: when a request arrives, compare its HTTP method and URL path against a list of registered routes and call the first handler that matches.

HTTP MethodExample PathTypical Action
GET/usersList resources
POST/usersCreate a resource
PUT/users/:idReplace a resource
PATCH/users/:idPartially update
DELETE/users/:idRemove a resource

Koa’s ctx object carries the matched route’s parameters, query string, and request body once you wire a router in.

Minimal Proof of Concept

Even without @koa/router you can route manually, but it gets unwieldy fast:

import Koa from "koa";

const app = new Koa();

app.use(async (ctx) => {
  if (ctx.method === "GET" && ctx.path === "/") {
    ctx.body = "home";
  } else {
    ctx.status = 404;
    ctx.body = "not found";
  }
});

app.listen(3000);

That is fine for one route. Ten routes later you will want a real router.

Up Next

The next lesson installs @koa/router, registers routes, and mounts it on the app.

Using @koa/router →