Introduction to Koa and Quick Start
🎯 Introduction
By the end of this article, you will understand what Koa is and how it differs from Express. You will also have a Koa project running your first hello world page in the browser. After Node.js and Express, this is our next step in exploring backend frameworks.
🧱 What Is Koa?
Koa is a lightweight web framework for Node.js, created by the team behind Express. As Express grew, the team designed a more streamlined framework: Koa.
Think of Express and Koa as two ways to furnish a home. Express is a furnished apartment, with routing and various features already in place. Koa is an empty apartment with the essentials installed: it provides core request handling, while you choose middleware for routing, request body parsing, and other features. It is a small space, but you control every part of it.
⚖️ Koa vs. Express
Both frameworks can serve backend APIs, but they differ in several ways:
| Aspect | Express | Koa |
|---|---|---|
| Framework scope | Includes routing and other features | Minimal core focused on requests and responses |
| Asynchronous code | Callback-based | Native async/await |
| Routing | Built in | Requires @koa/router |
| Request handling | Separate req and res objects | A single ctx context object |
| Middleware model | Linear execution | Onion model (covered later) |
For now, remember: Express provides more out of the box, while Koa has a smaller core and a more modern coding style. The routing and middleware concepts from the previous course carry over to Koa. Only the syntax changes, so getting started should feel familiar.
🚀 Set Up the Project
Create a koa-demo directory, open it in your terminal, initialize the project, and install Koa:
mkdir koa-demo
cd koa-demo
npm init -y
npm install koa
The examples in this article and throughout this course were written and verified with Node.js v22 LTS + Koa 3.2.1. Koa 3 fully embraces async/await, and its everyday syntax is largely the same as Koa 2. You can use the newer version directly.
To use import syntax, add "type": "module" to package.json:
{
"name": "koa-demo",
"version": "1.0.0",
"type": "module",
"dependencies": {
"koa": "^3.2.1"
}
}
🛠 Hello World
Create app.js with the following code:
import Koa from 'koa';
const app = new Koa();
// Middleware that handles every request
app.use(async (ctx) => {
ctx.body = 'Hello Koa';
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Here is what each part does:
new Koa()creates a Koa application instance, much likeexpress()in Express.app.use()registers middleware that runs for each incoming request. The callback receivesctx, a context object containing information about the request and response.ctx.bodyholds the content to send to the client. Assign a value directly; you do not need to callend()as you would with the native http module.app.listen(3000)starts the server and listens on port 3000.
Run this command in your terminal:
node app.js
Open http://localhost:3000 in your browser to see Hello Koa. During development, you can also use node --watch app.js to restart the server automatically when you save changes.
💡 What Can ctx.body Return?
Koa sets the response format automatically based on the type of value assigned to ctx.body:
app.use(async (ctx) => {
// Return a string
ctx.body = 'Hello, Koa';
});
app.use(async (ctx) => {
// Return an object: serialized as JSON with Content-Type set to application/json
ctx.body = { name: 'Alex', age: 18 };
});
Compare this with writing a JSON endpoint using the native http module: you had to call JSON.stringify and set Content-Type yourself. Koa handles both tasks, and non-ASCII text is returned without garbled characters because the framework handles encoding automatically.
ctx.body = {...} is the response pattern you will use most often.❓ Questions and Answers
Q1: Is Koa worth learning if I already know Express?
Yes. The two share many concepts, but Koa's async/await style and onion model have influenced many newer projects and frameworks, including Node.js server frameworks. Learning Koa helps you understand how middleware works at a deeper level.
Q2: Is routing inconvenient because Koa does not include it?
No. Install the official @koa/router package, and you can define routes with syntax very similar to Express. A later article covers routing in detail.
Q3: Is Koa 3 very different from Koa 2?
Everyday usage is largely the same: both use async/await. Koa 3 mainly updates internals and raises the minimum Node.js version. Use Koa 3 for this course.
Q4: Do I need to set response headers when assigning an object to ctx.body?
No. Koa sets Content-Type based on the value's type and automatically serializes objects and arrays as JSON. This makes it more convenient than the native http module.
🧪 Practice
- In your Koa project, change the response to a JSON object containing your name and today's date.
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
// Write your code here
});
app.listen(3000);
- Visit
http://localhost:3000in your browser and confirm that the response is displayed as JSON.
🎉 Your first Koa application is running! Next, we will explore Koa's central object, Context, and the useful properties available on ctx.
