Quick answer
Koa is a small Node.js web framework built by the team behind Express: it gives you a server, a context object, and async middleware, and leaves routing and body parsing to add-on packages. This post builds a small orders API with three routes, lists two seeded orders, creates a third, and fixes a real 400 error when the body never arrives.
A small shop in Karachi takes orders over the phone and writes each one in a paper notebook. When a customer calls to ask where an order is, someone flips pages. A simple web API would fix that: list orders, add one, fetch one by number. Express is the usual answer in Node.js, but Koa takes the same idea and makes it smaller: no built-in router, no built-in body parser, just a context object and middleware that reads like plain async code. The rest of this post builds that API, and breaks it once, so you see what a missing piece looks like.
What I would check before using it
My first check is whether the team is comfortable with async and await. Koa middleware is async functions all the way down: you await next() to hand control to the next middleware. A team that writes modern JavaScript will feel at home. The Build Your First REST API With Node.js and Express post shows the same three routes in Express.
My second check is how much the framework should include. Koa ships almost nothing: no router, no body parser, no static file serving. Every new project starts with the same three installs: koa, @koa/router, and koa-bodyparser. If the team wants routing and parsing in the box, look at Fastify: A Fast Node API Without the Ceremony, which includes both.
My third check is error handling. Koa catches errors thrown in middleware and turns them into a 500, and the app can listen for the error event and log it. That is a clean default, but the team still has to decide what each client-facing failure returns: a missing order is a 404, a bad body is a 400, and the demo returns those explicitly.
My fourth check is where the data lives. The demo keeps orders in an array in memory, so every restart wipes the shop. That is fine for learning, and the wrong design for a shop that takes real money. A demo that forgets is not a service that remembers.
My verdict, as judgement: adopt Koa when the team writes modern Node.js and wants a small core they can shape. Skip it when the team wants batteries included, or when async code is still new. The recommendation flips the moment the API needs an admin panel and sessions on day one.
Three orders, one API, and a body that never arrived
Three orders belong to one small shop: Ayesha buys a kurta and a dupatta for Rs 12,400, Bilal buys sneakers for Rs 7,800, and Hina buys a handbag and a wallet for Rs 9,600. The first two are seeded at startup; Hina's arrives later, through the API.
One file holds the whole API: the orders live in an array, three routes cover list, create, and fetch by id, and a small logger middleware prints each request with its status. The create route checks the body and answers 400 when a field is missing.
// Orders API for The Practical Developer (Koa demo).
//
// A small online shop exposes three routes with Koa:
// GET /orders list every order
// POST /orders create an order from a JSON body
// GET /orders/:id fetch one order by id
//
// Run from this folder:
// node server.js (listens on http://127.0.0.1:3000)
// curl http://127.0.0.1:3000/orders
const Koa = require("koa");
const Router = require("@koa/router");
const bodyParser = require("koa-bodyparser");
const app = new Koa();
const router = new Router();
const orders = [
{ id: 101, customer: "Ayesha", items: ["kurta", "dupatta"], total: 12400 },
{ id: 102, customer: "Bilal", items: ["sneakers"], total: 7800 },
];
let nextId = 103;
app.use(async (ctx, next) => {
const started = Date.now();
await next();
const ms = Date.now() - started;
console.log(`${ctx.method} ${ctx.url} -> ${ctx.status} (${ms}ms)`);
});
app.use(bodyParser());
router.get("/orders", (ctx) => {
ctx.body = orders;
});
router.get("/orders/:id", (ctx) => {
const order = orders.find((o) => o.id === Number(ctx.params.id));
if (!order) {
ctx.status = 404;
ctx.body = { error: "order not found" };
return;
}
ctx.body = order;
});
router.post("/orders", (ctx) => {
const body = ctx.request.body;
if (!body || !body.customer || !Array.isArray(body.items) || typeof body.total !== "number") {
ctx.status = 400;
ctx.body = { error: "order needs a customer, items, and a total number" };
return;
}
const order = { id: nextId, customer: body.customer, items: body.items, total: body.total };
nextId += 1;
orders.push(order);
ctx.status = 201;
ctx.body = order;
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log("Koa server listening on http://127.0.0.1:3000");
});
Here is the real output: the list returns the two seeded orders, then Hina's order goes wrong, with the first POST returning 400 even though the JSON body looks right.
$ node server.js
Koa server listening on http://127.0.0.1:3000
$ curl http://127.0.0.1:3000/orders
[{"id":101,"customer":"Ayesha","items":["kurta","dupatta"],"total":12400},{"id":102,"customer":"Bilal","items":["sneakers"],"total":7800}]
$ curl -X POST http://127.0.0.1:3000/orders -H 'Content-Type: application/json' -d '{"customer":"Hina","items":["handbag","wallet"],"total":9600}'
{"error":"order needs a customer, items, and a total number"}
HTTP status: 400
The thing that went wrong is the body parser, or rather the lack of one. Koa core never reads the request body, so ctx.request.body is undefined, and the validation in the create route rejects the request. The fix is two lines: require koa-bodyparser and call app.use(bodyParser()) before the routes, so the body is parsed before any handler reads it. The Hono: One Small API That Runs Almost Anywhere post shows a framework that parses the body for you. With the parser in place, the same request returns 201 with order 103, fetching it returns 200, and asking for order 999 returns 404 with a short JSON error instead of a crash.
$ curl -X POST http://127.0.0.1:3000/orders -H 'Content-Type: application/json' -d '{"customer":"Hina","items":["handbag","wallet"],"total":9600}'
{"id":103,"customer":"Hina","items":["handbag","wallet"],"total":9600}
HTTP status: 201
$ curl http://127.0.0.1:3000/orders/103
{"id":103,"customer":"Hina","items":["handbag","wallet"],"total":9600}
HTTP status: 200
$ curl http://127.0.0.1:3000/orders/999
{"error":"order not found"}
HTTP status: 404
Common mistakes and how to fix them
First, forgetting koa-bodyparser, the bug from the demo. The symptom is a 400 with "order needs a customer, items, and a total number" for a request whose JSON looks right. The fix is to register the parser before the routes.
Second, forgetting await next() in middleware. The symptom is a 404 with "Not Found" for a route that exists, because control never reaches the router. The fix is to await next() in every middleware that passes control on, as the logger does.
Third, comparing ctx.params.id with === to a number. The symptom is every fetch returning 404 with "order not found", even for /orders/101, because params arrive as strings. The fix is to convert first: Number(ctx.params.id), as the demo does.
Fourth, sending a POST without a Content-Type: application/json header. The symptom is the same 400 as the first mistake, because the parser only reads bodies marked as JSON. The fix is to send that header with every POST.
Frequently Asked Questions
Is Koa the same as Express? No. They share a team, not a design. Express gives you req and res and a built-in router; Koa gives you one context object, ctx, and async middleware, with routing left to @koa/router. Koa is the smaller core; Express is the fuller box.
Do I need @koa/router and koa-bodyparser? Yes, for this kind of API. Koa core has no router and never reads the request body. The demo uses koa 3.3.0, @koa/router 15.7.1, and koa-bodyparser 4.4.1, and the parser must be registered before the routes.
Can Koa serve HTML as well as JSON? Yes. A handler can set ctx.body to a string of HTML and ctx.type to text/html; the demo returns JSON only.
What happens when middleware throws an error? Koa catches it, emits an error event on the app, and answers 500. Listen with app.on("error", ...) to log it, and return 400 or 404 yourself for failures a client can fix.
What to remember
- Koa core is small: no router, no body parser, just ctx and middleware.
- Register koa-bodyparser before the routes, or ctx.request.body stays undefined.
- Every middleware that passes control on must await next().
- Route params arrive as strings; convert with Number() before comparing to a number.
- Return proper statuses: 201 for a created order, 404 for a missing one, 400 for a bad body.
Where this leaves you
Koa earns its place the day a Node.js API needs to stay small and readable. The demo proved the three things that matter: two seeded orders listed as JSON, a request with no body parser rejected with a clear 400, and the same request creating order 103 with a 201 once the parser was in place. The framework did not hide the missing piece; it answered 400. Start with three routes and an in-memory list, add a database when the orders must survive a restart, and keep the middleware chain honest so every request reaches the router.
Further reading
- Koa docs
- Koa on GitHub
- @koa/router on GitHub
- koa-bodyparser on GitHub
- Build Your First REST API With Node.js and Express
- Fastify: A Fast Node API Without the Ceremony
- Hono: One Small API That Runs Almost Anywhere
- Socket.IO
- Gin Go Tutorial: Build Fast APIs With Very Little Code
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Top comments (0)